Java IO操作:文件读写问题实例分析

原创 逃离我推掉我的手 2024-11-23 06:33 124阅读 0赞

在Java编程中,IO(Input/Output)操作主要涉及文件的读取、写入以及文件的各种属性管理。以下是一些具体问题实例和分析:

  1. 文件读写:
    ```java
    import java.io.File;
    import java.io.IOException;

public class FileReadWrite {
public static void main(String[] args) {
// 读文件
try {
File file = new File(“example.txt”);
String content = readFile(file);
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}

  1. // 写文件
  2. try {
  3. String newContent = "Updated content!";
  4. writeToFile(newContent, "updated_example.txt"));
  5. System.out.println("File updated successfully.");
  6. } catch (IOException i) {
  7. i.printStackTrace();
  8. System.out.println("Error occurred while updating file.");
  9. }
  10. }
  11. // 读文件
  12. private static String readFile(File file) throws IOException {
  13. StringBuilder content = new StringBuilder();
  14. try (BufferedReader br = new BufferedReader(new FileReader(file)))) {
  15. String line;
  16. while ((line = br.readLine()) != null)) {
  17. content.append(line).append("\n");
  18. }
  19. }
  20. return content.toString().trim(); // 去除末尾的空格
  21. }
  22. // 写文件
  23. private static void writeToFile(String content, String fileName) throws IOException {
  24. File file = new File(fileName);
  25. try (PrintWriter writer = new PrintWriter(file)) {
  26. writer.write(content);
  27. writer.flush(); // 确保内容立即写入磁盘
  28. }
  29. }

}

  1. 2. 文件属性管理:
  2. ```java
  3. import java.io.File;
  4. import java.io.IOException;
  5. public class FileAttributeManagement {
  6. public static void main(String[] args) throws IOException {
  7. // 获取文件属性
  8. File file = new File("example.txt");
  9. String fileName = file.getName();
  10. long fileSize = file.length(); // 文件大小
  11. System.out.println("File Name: " + fileName);
  12. System.out.println("File Size (in bytes): " + fileSize);
  13. // 修改文件属性
  14. if (file.exists() && !file.isDirectory())) {
  15. file.setLength(1024); // 设置文件大小为1KB
  16. System.out.println("File size modified successfully to 1 KB.");
  17. } else {
  18. System.out.println("Error: File does not exist or is a directory.");
  19. }
  20. }
  21. }

总结:在进行Java IO操作时,理解文件读写的基本流程以及如何使用java.io包中的类是至关重要的。

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

发表评论

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

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

相关阅读