除非我指定绝对路径(C:\ User \Documents等),否则FileInputStream(" hello.txt")不起作用 [英] FileInputStream("hello.txt"), doesn't work unless I specify an absolute path (C:\User\Documents etc)
本文介绍了除非我指定绝对路径(C:\ User \Documents等),否则FileInputStream(" hello.txt")不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嗨有没有办法让FileInputStream在同一目录下读取 hello.txt
而不指定路径?
Hi is there any way I can get FileInputStream to read hello.txt
in the same directory without specifying a path?
package hello/
helloreader.java
hello.txt
我的错误信息:错误:。\ hello.txt(系统找不到指定的文件)
推荐答案
您可以使用相对路径读取文件。
You can read file with relative path like.
File file = new File("./hello.txt");
-
YourProject
YourProject
- > bin
- > hello.txt
->hello.txt
- > .classpath
->.classpath
- > .project
->.project
这是作品
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(); } } } }
这篇关于除非我指定绝对路径(C:\ User \Documents等),否则FileInputStream(" hello.txt")不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文