完整代码:
在下面的示例中, 我们将一串字符串写入到一个文件。
为了将String转换为字节数组, 我们使用了字符串类的getBytes () 方法.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteFileDemo {
public static void main(String[] args) {
FileOutputStream fos = null;
File file;
String mycontent = "需要写入文件的数据" + " to be written into the file";
try {
// 指定写入文件的路径
file = new File("D:/myfile.txt");
fos = new FileOutputStream(file);
/* 先检测文件是否存在,如果不存在则先创建*/
if (!file.exists()) {
file.createNewFile();
}
/*
* 字符串的内容没法直接写到文件,我们需要先使用getBytes转换为bytes。
*/
byte[] bytesArray = mycontent.getBytes();
fos.write(bytesArray);
fos.flush();
System.out.println("File Written Successfully");
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (IOException ioe) {
System.out.println("Error in closing the Stream");
}
}
}
}