Skip to content

Latest commit

 

History

History
76 lines (61 loc) · 2.57 KB

84.md

File metadata and controls

76 lines (61 loc) · 2.57 KB

如何在 java 中使用FileOutputStream写入文件

原文: https://beginnersbook.com/2014/01/how-to-write-to-a-file-in-java-using-fileoutputstream/

之前我们看过如何在 Java 中创建一个文件。在本教程中,我们将看到如何使用FileOutputStream在 java 中写入文件。我们将使用FileOutputStreamwrite()方法将内容写入指定的文件。这是write()方法的签名。

public void write(byte[] b) throws IOException

它将指定字节数组中的b.length字节写入此文件输出流。如您所见,此方法需要字节数组才能将它们写入文件。因此,在将内容写入文件之前,我们需要将内容转换为字节数组。

完整代码:写入文件

在下面的例子中,我们将String写入文件。要将String转换为字节数组,我们使用StringgetBytes()方法

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

参考:

FileOutputStream - JavaDoc