java中怎么使用new FileOutStream(file,true)将数据添加到一个已经存在的文件中
时间: 2024-03-16 08:47:08 浏览: 16
在Java中,使用`FileOutputStream`类的构造函数`FileOutputStream(File file, boolean append)`可以将数据添加到一个已经存在的文件中。其中,`file`参数是指向要追加数据的文件的`File`对象,`append`参数是一个布尔值,用于指定是否在文件末尾追加数据。
示例代码如下:
```java
import java.io.*;
public class AppendDataToFile {
public static void main(String[] args) {
try {
//创建一个File对象
File file = new File("data.txt");
//创建一个FileOutputStream对象,并指定在文件末尾追加数据
FileOutputStream fos = new FileOutputStream(file, true);
//创建一个要追加的数据
String data = "Hello, world!";
//将数据转换为字节数组
byte[] bytes = data.getBytes();
//将数据追加到文件末尾
fos.write(bytes);
//关闭文件输出流
fos.close();
System.out.println("Data appended to file successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在上面的示例中,我们创建了一个`File`对象,然后创建了一个`FileOutputStream`对象,并将`append`参数设为`true`,表示在文件末尾追加数据。接着,我们将要追加的数据转换为字节数组,然后使用`write`方法将数据追加到文件末尾。最后,我们关闭了文件输出流,并打印了一条成功追加数据的消息。
相关推荐
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)