6

嗨,有什么方法可以让 FileInputStreamhello.txt在不指定路径的情况下在同一目录中读取?

package hello/
    helloreader.java
    hello.txt

我的错误信息:Error: .\hello.txt (The system cannot find the file specified)

4

5 回答 5

11

您可以读取具有相对路径的文件,例如。

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

    ->垃圾箱

    ->你好.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();
            }
        }
    }
}
于 2012-09-13T12:46:51.690 回答
9

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

于 2012-09-13T12:35:39.420 回答
4

当您打开“hello.txt”时,您将在进程的当前工作目录中打开一个文件。即程序是从哪里运行的,而不是你的jar 所在的位置或其他目录。

于 2012-09-13T12:38:23.727 回答
3

当您使用 path 打开文件时hello.txt,该文件hello.txt应位于执行java命令的同一目录中,即工作目录。并且您可以在运行 Java 程序时使用以下代码打印工作目录:

System.out.println(System.getProperty("user.dir"));

假设您像这样执行代码java hello.helloreader,那么您应该使用以下路径来获取hello.txt

new FileInputStream("hello/hello.txt")
于 2012-09-13T12:47:59.747 回答
0

您可以尝试 System.getProperty("dir") 显示您的当前目录,您将知道如何编写文件路径

于 2012-09-13T12:47:49.443 回答