fileoutputstream转Fileinputstream
时间: 2023-12-28 14:25:41 浏览: 55
在Java中,可以使用FileOutputStream将数据写入文件,然后使用FileInputStream从文件中读取数据。下面是一个示例代码:
```java
import java.io.*;
public class FileIOExample {
public static void main(String[] args) {
String fileName = "example.txt";
String content = "Hello, world!";
// 使用FileOutputStream写入数据到文件
try (FileOutputStream fos = new FileOutputStream(fileName)) {
byte[] bytes = content.getBytes();
fos.write(bytes);
System.out.println("数据写入成功!");
} catch (IOException e) {
e.printStackTrace();
}
// 使用FileInputStream从文件中读取数据
try (FileInputStream fis = new FileInputStream(fileName)) {
byte[] bytes = new byte[fis.available()];
fis.read(bytes);
String readContent = new String(bytes);
System.out.println("从文件中读取的数据为:" + readContent);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这段代码首先使用FileOutputStream将字符串"Hello, world!"写入到名为"example.txt"的文件中。然后使用FileInputStream从该文件中读取数据,并将读取到的内容打印出来。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)