之前我们看过如何在 Java中创建一个文件。在本教程中,我们将看到如何使用FileOutputStream
在 java 中写入文件。我们将使用FileOutputStream
的write()
方法将内容写入指定的文件。这是write()
方法的签名。
public void write(byte[] b) throws IOException
它将指定字节数组中的b.length
字节写入此文件输出流。如您所见,此方法需要字节数组才能将它们写入文件。因此,在将内容写入文件之前,我们需要将内容转换为字节数组。
完整代码:写入文件
在下面的例子中,我们将String
写入文件。要将String
转换为字节数组,我们使用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 = "This is my Data which needs" +
" to be written into the file";
try {
//Specify the file path here
file = new File("C:/myfile.txt");
fos = new FileOutputStream(file);
/* This logic will check whether the file
* exists or not. If the file is not found
* at the specified location it would create
* a new file*/
if (!file.exists()) {
file.createNewFile();
}
/*String content cannot be directly written into
* a file. It needs to be converted into 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");
}
}
}
}
输出:
File Written Successfully