FileOutputStream
时间: 2023-10-22 14:06:15 浏览: 41
FileOutputStream is a class in Java that is used to write data to a file. It is part of the java.io package and is used for writing binary data to a file.
To use FileOutputStream, you need to create an instance of the class and specify the name of the file you want to write to. You can then use various write methods to write data to the file.
Here is an example of using FileOutputStream to write a string to a file:
```
import java.io.*;
public class WriteToFile {
public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream("output.txt");
String str = "Hello, world!";
byte[] bytes = str.getBytes();
fos.write(bytes);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
In this example, we create a FileOutputStream object and pass the name of the file we want to write to as a parameter. We then convert the string "Hello, world!" to a byte array using the getBytes() method, and write it to the file using the write() method. Finally, we close the file using the close() method.
Note that FileOutputStream will overwrite the contents of the file if it already exists. If you want to append data to the end of the file instead, you can use the FileOutputStream constructor that takes a second boolean parameter, which specifies whether to append to the file or not.
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)