java 在Linux下写文件
时间: 2023-12-10 22:42:10 浏览: 41
在Linux下使用Java写文件,可以使用Java标准库提供的FileOutputStream和PrintWriter类。下面是一个简单的例子:
```java
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
public class WriteToFileExample {
public static void main(String[] args) {
String filename = "/path/to/file.txt";
String content = "Hello, world!";
try {
File file = new File(filename);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(fos);
pw.write(content);
pw.close();
fos.close();
System.out.println("File written successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在上面的例子中,我们首先指定了要写入的文件路径和内容。然后,我们创建一个File对象,并检查该文件是否存在。如果文件不存在,我们使用createNewFile()方法创建一个新文件。
接下来,我们创建一个FileOutputStream对象,它可以将字节写入文件中。我们还创建了一个PrintWriter对象,它可以将文本写入文件中。
最后,我们使用write()方法将内容写入文件中,并关闭PrintWriter和FileOutputStream对象。
相关推荐
![](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)
![](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)