mei*_*ryo 5 java fileinputstream
您有没有办法让FileInputStream hello.txt在同一目录中读取而不指定路径?
package hello/
helloreader.java
hello.txt
Run Code Online (Sandbox Code Playgroud)
我的错误信息: Error: .\hello.txt (The system cannot find the file specified)
swe*_*mon 10
您可以使用相对路径读取文件.
File file = new File("./hello.txt");
Run Code Online (Sandbox Code Playgroud)
YourProject
- >斌
- > hello.txt的
- >类路径
- >项目
这是作品
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();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用YourClassName.class.getResourceAsStream("Filename.txt"),但您的文本文件必须与文件位于同一目录/包中YourClassName.