文件无法在Java中打开

时间:2013-06-21 21:53:36

标签: java eclipse inputstream

我试图阅读带有内容的简单文本文件 的 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 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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

        }
    }   
}

答案 2 :(得分: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();
    }   
}

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

答案 3 :(得分:0)

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

感谢您的帮助!