Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/329.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/25.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 fileinputstream没有这样的文件或目录_Java_File Io_Bufferedreader - Fatal编程技术网

Java fileinputstream没有这样的文件或目录

Java fileinputstream没有这样的文件或目录,java,file-io,bufferedreader,Java,File Io,Bufferedreader,我正在尝试学习如何使用从文本文件逐行读取。即使我把txt文件放在同一个src中,控制台也总是显示错误-没有这样的文件或目录 public class ddd { public static void main(String[] args) { FileInputStream fis = null; BufferedReader reader = null; try { fis = new FileInputStream("/dd/src/com/dd/i

我正在尝试学习如何使用从文本文件逐行读取。即使我把txt文件放在同一个src中,控制台也总是显示错误-
没有这样的文件或目录

public class ddd {

public static void main(String[] args) {
    FileInputStream fis = null;
    BufferedReader reader = null;
    try {
        fis = new FileInputStream("/dd/src/com/dd/input.txt");
        reader = new BufferedReader(new InputStreamReader(fis));
        System.out
                .println("Reading File line by line using BufferedReader");
        String line = reader.readLine();
        while (line != null) {
            System.out.println(line);
            line = reader.readLine();
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    } finally {
        try {
            reader.close();
            fis.close();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }

    }
}

}问题可能在这里:

"/dd/src/com/dd/input.txt"
至少在Linux上,这是一条绝对路径。您可能需要的是相对于项目根的路径:

"src/com/dd/input.txt"
或者,如果要将此文件打包到程序中,请使用资源流而不是原始的
FileInputStream

InputStream is = ddd.class.getResourceAsStream("input.txt");

问题可能在这里:

"/dd/src/com/dd/input.txt"
至少在Linux上,这是一条绝对路径。您可能需要的是相对于项目根的路径:

"src/com/dd/input.txt"
或者,如果要将此文件打包到程序中,请使用资源流而不是原始的
FileInputStream

InputStream is = ddd.class.getResourceAsStream("input.txt");

您需要使用相对路径,例如
“src/com/dd/input.txt”
。我试过了,效果很好

输出


我的
input.txt
hhh内容。

您需要使用相对路径,例如
“src/com/dd/input.txt”
。我试过了,效果很好

输出


我的
input.txt
hhh内容。

我建议使用当前工作目录系统.getProperty(“user.dir”))来查找您当前的工作位置。这被证明是我在学习使用文件输入/输出时遇到的最大问题之一。我可能建议使用当前的工作目录System.getProperty(“user.dir”))来查找当前的工作位置。这是我在学习使用文件输入/输出时遇到的最大问题之一。