java 新建线程保存文件
时间: 2023-10-17 14:07:54 浏览: 51
以下是Java代码示例,用于新建线程保存文件:
```java
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class SaveFileThread extends Thread {
private byte[] data;
private String fileName;
public SaveFileThread(byte[] data, String fileName) {
this.data = data;
this.fileName = fileName;
}
public void run() {
try {
FileOutputStream fos = new FileOutputStream(new File(fileName));
fos.write(data);
fos.close();
System.out.println("File saved successfully: " + fileName);
} catch (IOException e) {
System.out.println("Error saving file: " + fileName);
e.printStackTrace();
}
}
}
```
在主程序中,可以使用以下代码来启动新线程并保存文件:
```java
byte[] data = // 从网络或其他来源获取数据
String fileName = "example.txt";
SaveFileThread saveFileThread = new SaveFileThread(data, fileName);
saveFileThread.start();
```
这将启动一个新线程,该线程将在后台保存数据到指定的文件中。这样可以确保主程序不会因为保存文件而被阻塞。
相关推荐
![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_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)