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

> 原文： [https://beginnersbook.com/2014/01/how-to-write-to-a-file-in-java-using-fileoutputstream/](https://beginnersbook.com/2014/01/how-to-write-to-a-file-in-java-using-fileoutputstream/)

之前我们看过如何[在 Java](https://beginnersbook.com/2014/01/how-to-create-a-file-in-java/) 中创建一个文件。在本教程中，我们将看到如何使用`FileOutputStream`在 java 中写入文件。我们将使用`FileOutputStream`的[`write()`方法](https://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html#write(byte[]))将内容写入指定的文件。这是`write()`方法的签名。

```java
public void write(byte[] b) throws IOException
```

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

## 完整代码：写入文件

在下面的例子中，我们将`String`写入文件。要将`String`转换为字节数组，我们使用[`String`类](https://beginnersbook.com/2013/12/java-strings/)的[`getBytes()`方法](https://beginnersbook.com/2013/12/java-string-getbytes-method-example/)。

```java
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");
	  }
       }
   }
}
```

输出：

```java
File Written Successfully
```

#### 参考：

[`FileOutputStream` - JavaDoc](https://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html)