使用Java的IO流处理文件读写操作示例

原创 亦凉 2024-10-16 10:15 165阅读 0赞

在Java中,我们可以使用InputStreamOutputStream来处理文件读写。以下是一些基本示例:

  1. 文件读取
    ```java
    import java.io.*;

public class FileReader {
public static void main(String[] args) {
String fileName = “example.txt”; // 你要读的文件名

  1. try (BufferedReader br = new BufferedReader(new FileReader(fileName)))) {
  2. System.out.println("File contents:");
  3. String line;
  4. while ((line = br.readLine()) != null) {
  5. System.out.println(line);
  6. }
  7. } catch (FileNotFoundException e) {
  8. e.printStackTrace();
  9. System.out.println("File not found.");
  10. }
  11. }

}

  1. 2. **文件写入**:
  2. ```java
  3. import java.io.*;
  4. public class FileWriter {
  5. public static void main(String[] args) {
  6. String fileName = "example.txt"; // 你要写入的文件名
  7. String content = "This is a test file written using Java IO."; // 要写入的内容
  8. try (PrintWriter writer = new PrintWriter(new FileWriter(fileName)))) {
  9. writer.println(content);
  10. System.out.println("File written successfully.");
  11. } catch (FileNotFoundException e) {
  12. e.printStackTrace();
  13. System.out.println("Error: File not found.");
  14. }
  15. }
  16. }

这些示例展示了如何使用Java的InputStreamOutputStream来处理文件读写操作。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,165人围观)

还没有评论,来说两句吧...

相关阅读