java String转File
时间: 2023-07-05 08:31:50 浏览: 52
在Java中,您可以使用FileWriter类或FileOutputStream类将字符串写入文件。
以下是一个使用FileWriter的示例代码:
```java
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class StringToFile {
public static void main(String[] args) {
String str = "Hello, world!";
// 将字符串写入文件
try (FileWriter writer = new FileWriter(new File("data.txt"))) {
writer.write(str);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在上面的示例中,我们使用FileWriter类将字符串"Hello, world!"写入了data.txt文件中。需要注意的是,FileWriter类会在写入时将字符串转换为字符流,因此对于二进制数据的写入,您应该使用FileOutputStream类。
以下是一个使用FileOutputStream的示例代码:
```java
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class StringToFile {
public static void main(String[] args) {
String str = "Hello, world!";
// 将字符串转换为字节数组
byte[] data = str.getBytes();
// 将字节数组写入文件
try (FileOutputStream fos = new FileOutputStream(new File("data.txt"))) {
fos.write(data);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在上面的示例中,我们使用FileOutputStream类将字符串"Hello, world!"转换为字节数组,并将字节数组写入了data.txt文件中。需要注意的是,在使用完FileOutputStream后,需要调用close方法关闭流。
相关推荐
![](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)