0

我正在尝试使用内容 input.txt读取一个简单的文本文件

Line 1
Line 2
Line 3

但它总是会出现异常并打印错误。

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String args[]){

        List<String> text = new ArrayList<String>();
        try{
            BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
            for (String line; (line = reader.readLine()) != null; ) {
                 text.add(line);
            }
            System.out.println(text.size()); //print how many lines read in
            reader.close();
        }catch(IOException e){
            System.out.println("ERROR");
        }
    }   
}

如果这有所作为,我将使用 Eclipse 作为我的 IDE。我在http://www.compileonline.com/compile_java_online.php上试过这段代码 ,它运行良好,为什么不能在 Eclipse 中运行?

4

4 回答 4

1

给出完整的文件路径,如"C:\\folder_name\\input.txt"或将 input.txt 放在 Eclipse 项目的 src 目录中。

于 2013-06-21T21:59:28.053 回答
1
public class Main {
    public static void main(String args[]){

        List<String> text = new ArrayList<String>();
        try{
            BufferedReader reader = new BufferedReader(
                    new FileReader("input.txt"));  //<< your problem is probably here, 
            //More than likely you have to supply a path the input file.
            //Something like "C:\\mydir\\input.txt"
            for (String line; (line = reader.readLine()) != null; ) {
                 text.add(line);
            }
            System.out.println(text.size()); //print how many lines read in
            reader.close();
        }catch(IOException e){
            System.out.println("ERROR"); //This tells you nothing.
            System.out.println(e.getMessage());  //Do this
            //or 
            e.printStackTrace(); //this or both

        }
    }   
}
于 2013-06-21T21:59:48.337 回答
1

你很可能有一条糟糕的道路。考虑这个主要的:

public class Main {
    public static void main(String args[]) throws Exception {

        List<String> text = new ArrayList<String>();

        BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
        for (String line; (line = reader.readLine()) != null; ) {
             text.add(line);
        }
        System.out.println(text.size()); //print how many lines read in
        reader.close();
    }   
}

“抛出异常”添加让您可以专注于代码,并在以后考虑更好的错误处理。还可以考虑使用File f = new File("input.txt")并使用它,因为它允许您打印出f.getAbsolutePath()它告诉您它实际查找的文件名。

于 2013-06-21T22:03:28.580 回答
0

改变input.txt解决src\\input.txt问题!我猜这是因为当前目录实际上不是其父目录的 src 文件夹,

谢谢您的帮助!

于 2013-06-21T22:14:59.813 回答