Java FileInputStream(“hello.txt”),不';除非指定绝对路径(C:\User\Documents等),否则无法工作

Java FileInputStream(“hello.txt”),不';除非指定绝对路径(C:\User\Documents等),否则无法工作,java,fileinputstream,Java,Fileinputstream,嗨,有没有办法让FileInputStream读取同一目录中的hello.txt,而不指定路径 package hello/ helloreader.java hello.txt 我的错误消息:error:。\hello.txt(系统找不到指定的文件)您可以使用YourClassName.class.getResourceAsStream(“Filename.txt”),但您的文本文件必须与YourClassName文件位于同一目录/包中。打开“hello.txt”您正在当前进

嗨,有没有办法让FileInputStream读取同一目录中的
hello.txt
,而不指定路径

package hello/
    helloreader.java
    hello.txt

我的错误消息:
error:。\hello.txt(系统找不到指定的文件)

您可以使用
YourClassName.class.getResourceAsStream(“Filename.txt”)
,但您的文本文件必须与
YourClassName
文件位于同一目录/包中。

打开“hello.txt”您正在当前进程中打开一个文件。i、 e.程序运行的位置,而不是jar所在的位置或其他目录。

您可以使用类似的相对路径读取文件

File file = new File("./hello.txt");
  • 你的项目

    ->垃圾箱

    ->hello.txt

    ->.classpath

    ->.项目

这是我的作品

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class fileInputStream {

    public static void main(String[] args) {

        File file = new File("./hello.txt");
        FileInputStream fis = null;

        try {
            fis = new FileInputStream(file);

            System.out.println("Total file size to read (in bytes) : "
                    + fis.available());

            int content;
            while ((content = fis.read()) != -1) {
                // convert to char and display it
                System.out.print((char) content);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null)
                    fis.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

您可以尝试System.getProperty(“dir”)来显示当前目录,并且您将知道如何编写文件路径。当您使用path
hello.txt
打开文件时,文件
hello.txt
应该位于执行
java
命令的同一目录中,即工作目录。运行Java程序时,可以使用以下代码打印工作目录:

System.out.println(System.getProperty(“user.dir”);
假设您像这样执行代码
java hello.helloreader
,那么您应该使用以下路径来获取
hello.txt

newfileinputstream(“hello/hello.txt”)

在什么的同一目录中?如果文件在当前工作目录中,它应该可以工作。“不工作”,您有任何异常吗?是的,有一种方法:)只要确保
hello.txt
文件与您的jar文件(如果您有)处于同一级别,或者如果您仍在开发项目,则确保它与您的jar文件处于同一级别(和你的封装课不一样)我"我使用eclipse,.txt文件与.java文件在同一个包中。谢谢。这只发生在某些IDE上吗?我已经尝试了很好的旧文本编辑器和命令行,效果很好。如果要将web项目部署为.war文件,将java类放在web-INF/classes文件夹中,这是行不通的,现在很多人都这样做。it应该是@khotyn上面提到的“user.dir”