如何在Java中读取文本文件?

huangapple go评论63阅读模式
英文:

How to read TextFiles in java?

问题

以下是翻译好的代码部分:

// 导入文件
import java.io.*;

// 导入文件读取器
import java.io.FileReader;

// 导入处理错误的 IOException
import java.io.IOException;

// 创建类和方法
class Main {
 public static void main(String[] args) {

    // 开始一个 try-catch 块
    try {

      // 初始化新对象
      FileWriter fw = new FileWriter("FirstNames");
      BufferedWriter bw = new BufferedWriter(fw);

      // 创建一个字符串数组来存储名字
      String names[] = new String[] { "Hussain", "Ronald", "John", "James", "Robert", "Michael", "William", "David",
          "Joseph", "Daniel" };

      // 将名字输出到文本文件中
      for (int x = 0; x < 10; x++){
      bw.write(names[x]);
      bw.newLine();
      }

      bw.close();
      fw.close();

      // 捕捉任何错误
    } catch (Exception e) {
      System.out.println("发生错误!");
    }

    
    // 从这里开始出现问题: 
    

    // 创建另一个 try-catch 块来读取文件
    try {

      // 初始化新对象
      FileReader fr = new FileReader("FirstNames.txt");
      BufferedReader br = new BufferedReader(fr);
      String line = br.readLine();

      // 开始一个循环来输出每一行
      while (line != null) {
        System.out.println(line);
        line = br.readLine();
      }
     
      br.close();
      fr.close();

    } catch (NullPointerException e1) { // 我现在将它设为 NullPointerException 只是为了看看我现在得到的错误
      // System.out.println("发生错误!");
        }
      }
    }

请注意,我只翻译了你提供的代码部分,不包括问题和图片链接。如果需要进一步帮助,请随时提问。

英文:

so I was tasked with writing and reading TextFiles in java, and I managed to successfully write a TextFile and display the contents (First Names) in the new file called "FirstNames". I am supposed to use the try-catch block to accomplish this task, however, I am unable to successfully read the file back, as it produces some errors that I am unable to fix. Any help would be greatly appreciated!

My Code:

// Import file
Import java.io.*;
// Import file reader
import java.io.FileReader;
// Import IOException to handle any errors
import java.io.IOException;
// Create class and method
class Main {
public static void main(String[] args) {
// Start a try-catch block
try {
// Initialize the new objects
FileWriter fw = new FileWriter(&quot;FirstNames&quot;);
BufferedWriter bw = new BufferedWriter(fw);
// Create a String array to store the first names
String names[] = new String[] { &quot;Hussain&quot;, &quot;Ronald&quot;, &quot;John&quot;, &quot;James&quot;, &quot;Robert&quot;, &quot;Michael&quot;, &quot;William&quot;, &quot;David&quot;,
&quot;Joseph&quot;, &quot;Daniel&quot; };
// Output the first names in the textfile
for (int x = 0; x &lt; 10; x++){
bw.write(names[x]);
bw.newLine();
}
bw.close();
fw.close();
// Catch any errors
} catch (Exception e) {
System.out.println(&quot;An error occured!&quot;);
}
// Experiencing issues starting from here: 
// Create another try-catch block to read the file
try {
// Initialize the new objects
FileReader fr = new FileReader(&quot;FirstNames.txt&quot;);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
// Start a while loop to output the line
while (line != null) {
System.out.println(line);
line = br.readLine();
}
br.close();
fr.close();
} catch (NullPointerException e1) { // I have put it to NullPointerException only to see the errors I&#39;m getting for now
// System.out.println(&quot;An Error Occured!&quot;);
}
}
}

My Output:

如何在Java中读取文本文件?

答案1

得分: 0

你的问题是你在编写代码时使用了 FirstNames,然后尝试读取 FirstNames.txt

我在下面进行了一些增强,使用了 Try-with-resources 来自动关闭资源,无需在使用后手动关闭资源。

我还将文件名替换为一个变量,该变量保存字符串名称。(在 IntelliJ 的重构菜单下选择 "extract to variable")

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

class Main {

    public static void main(String[] args) {
        // 通过使用文件名变量,可以减少错误的机会。
        String fileName = "FirstNames";
        
        try (FileWriter fw = new FileWriter(fileName)) {
            // 初始化新对象

            BufferedWriter bw = new BufferedWriter(fw);

            // 应该是一个 public static final String[] 类字段。
            String names[] = new String[]{"Hussain",
                    "Ronald",
                    "John",
                    "James",
                    "Robert",
                    "Michael",
                    "William",
                    "David",
                    "Joseph",
                    "Daniel"};

            // 在文本文件中输出名字
            for (String name : names) {
                bw.write(name);
                bw.newLine();
            }
            bw.close();
        } catch (IOException ex) {
            ex.printStackTrace(); // 读取堆栈跟踪以理解错误
        }

        // 现在尝试读取文件
        try (FileReader fr = new FileReader(fileName)){

            // 初始化新对象
            BufferedReader br = new BufferedReader(fr);

            String line;
            // 开始一个 while 循环来输出每一行
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }

            br.close();
            
        } catch (IOException e) {
            System.out.println("捕获与 br.readLine()、br.close() 和新的 FileReader 相关的错误");
            e.printStackTrace();
        }
    }
}

希望这些修改与你原始的代码不会差太远,还能保持理解上的连贯性。

正如其他人提到的,在实际情况下,你可能希望将所有/部分错误抛出到调用栈的更高层,以便可以由集中的错误处理程序处理(这样所有的错误处理逻辑都在一个地方,而不是分散在各处)。

目前我只是用了 ex.printStackTrace() 并允许继续执行。这可能会导致打印出多个堆栈跟踪,可能会令人困惑。

基本上从输出中的第一个错误开始,如果你修复了那个,你可能会解决所有问题,否则重新运行并查看控制台中的下一个第一个错误... 依此类推。最终当你修复了所有错误后,代码就会运行 如何在Java中读取文本文件?

英文:

Your problem was you were writing FirstNames and then trying to read FirstNames.txt

I've made some enhancements below to use Try-with-resources which offers the benefit of not having to close the resource at the end of use.

I've also replaced the file name with a single variable that holds the string name. ("extract to variable" under your refactor menu in IntelliJ)

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

class Main {

    public static void main(String[] args) {
        // By deduplicating the filename you will remove the chance for errors.
        String fileName = &quot;FirstNames&quot;;
        
        try (FileWriter fw = new FileWriter(fileName)) {
            // Initialize the new objects

            BufferedWriter bw = new BufferedWriter(fw);

            // should probably be a public static final String[] class field.
            String names[] = new String[]{&quot;Hussain&quot;,
                    &quot;Ronald&quot;,
                    &quot;John&quot;,
                    &quot;James&quot;,
                    &quot;Robert&quot;,
                    &quot;Michael&quot;,
                    &quot;William&quot;,
                    &quot;David&quot;,
                    &quot;Joseph&quot;,
                    &quot;Daniel&quot;};

            // Output the first names in the textfile
            for (String name : names) {
                bw.write(name);
                bw.newLine();
            }
            bw.close();
        } catch (IOException ex) {
            ex.printStackTrace(); // read the stack trace to understand the errors
        }

        // Now TRY reading the file
        try (FileReader fr = new FileReader(fileName)){

            // Initialize the new objects
            BufferedReader br = new BufferedReader(fr);

            String line;
            // Start a while loop to output the line
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }

            br.close();
            
        } catch (IOException e) {
            System.out.println(&quot;Catches errors related to br.readLine(), br.close() and new FileReader&quot;);
            e.printStackTrace();
        }
    }
}

Hopefully not too far removed from your original code that it still makes sense.

As others have mentioned, in a real-world situation, you may want to throw all/some errors higher up the call stack so they can be handled by a centralised error handler (so that all error handling logic is in one place rather than scattered all over the place).

At the moment I've just put ex.printStackTrace() and allowed execution to continue. This could result in multiple stack traces to be printed out which can be confusing.

Essentially start with the first error in the output and if you fix that, you may fix all the problems, otherwise re-run and look at the next first error in the console... and so on. Eventually when you've fixed all errors the code will run 如何在Java中读取文本文件?

huangapple
  • 本文由 发表于 2020年10月15日 04:33:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/64361108.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定