嗨,有什么方法可以让 FileInputStreamhello.txt
在不指定路径的情况下在同一目录中读取?
package hello/
helloreader.java
hello.txt
我的错误信息:Error: .\hello.txt (The system cannot find the file specified)
嗨,有什么方法可以让 FileInputStreamhello.txt
在不指定路径的情况下在同一目录中读取?
package hello/
helloreader.java
hello.txt
我的错误信息:Error: .\hello.txt (The system cannot find the file specified)
您可以读取具有相对路径的文件,例如。
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();
}
}
}
}
您可以使用YourClassName.class.getResourceAsStream("Filename.txt")
,但您的文本文件必须与您的YourClassName
文件位于同一目录/包中。
当您打开“hello.txt”时,您将在进程的当前工作目录中打开一个文件。即程序是从哪里运行的,而不是你的jar 所在的位置或其他目录。
当您使用 path 打开文件时hello.txt
,该文件hello.txt
应位于执行java
命令的同一目录中,即工作目录。并且您可以在运行 Java 程序时使用以下代码打印工作目录:
System.out.println(System.getProperty("user.dir"));
假设您像这样执行代码java hello.helloreader
,那么您应该使用以下路径来获取hello.txt
:
new FileInputStream("hello/hello.txt")
您可以尝试 System.getProperty("dir") 显示您的当前目录,您将知道如何编写文件路径