Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 逐行读取文本文件_Java_Eclipse_Text Files - Fatal编程技术网

Java 逐行读取文本文件

Java 逐行读取文本文件,java,eclipse,text-files,Java,Eclipse,Text Files,我这样试过,但找不到文本文件 try { FileInputStream fstream = new FileInputStream("textfile.txt"); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; // Read File

我这样试过,但找不到文本文件

try {
    FileInputStream fstream = new FileInputStream("textfile.txt");
    DataInputStream in = new DataInputStream(fstream);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
    // Read File Line By Line
    while ((strLine = br.readLine()) != null) {
        // Print the content on the console
        System.out.println(strLine);
    }
    // Close the input stream
    in.close();
} catch (Exception e) {// Catch exception if any
    System.err.println("Error: " + e.getMessage());
}

所有文件都在同一个软件包中。

您的文本文件在“培训师”软件包中,该软件包位于“src”内,因此当您请求时,必须使用
“src/trainer/textfile.txt”
。前面的
/
表示应用程序的根目录,例如,如果您没有导出到可运行的JAR,那么它是可选的

FileInputStream fstream = new FileInputStream("src/trainer/textfile.txt");

新建文件(“textfile.txt”).getAbsolutePath()
-这会打印出您期望的内容吗?如果找不到文本文件,请确保该文本文件确实存在于程序运行的目录中。尝试使用“/textfile.txt”请告诉我们您的文件结构eclipse在哪里运行您的程序并不总是显而易见的。我更喜欢存储相对于用户主文件夹的文件<代码>新文件(System.getProperty(“user.home”),“textfile.txt”)
尝试{FileInputStream fstream=new FileInputStream(“/trainer/textfile.txt”);DataInputStream in=new DataInputStream(fstream);BufferedReader br=new BufferedReader(new InputStreamReader(in));String strLine;//逐行读取文件,而((strLine=br.readLine())!=null){//在控制台System.out.println(strLine);}//关闭输入流in.Close();}捕获(异常e){//如果有任何System.err.println(“错误:+e.getMessage());}
是的,类似于Yes
错误:/trainer/textfile.txt(没有这样的文件或目录)
尝试在开始时不使用斜杠?否则将文件移动到源文件夹并使用“textfile.txt”好的,请稍候,我正在亲自尝试