Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何读取项目中的txt文件?_Java_File_Path - Fatal编程技术网

Java 如何读取项目中的txt文件?

Java 如何读取项目中的txt文件?,java,file,path,Java,File,Path,我想让我的项目中的任何文件都可以被任何用户读取,因为他们不会和我有相同的目录 所以我有这个: String filme = "somefile.txt" String datastr = ""; reader = new BufferedReader( new FileReader("C:/Path"+filename)); String line = reader.readLine(); while( line != null) { datastr +=

我想让我的项目中的任何文件都可以被任何用户读取,因为他们不会和我有相同的目录

所以我有这个:

String filme = "somefile.txt"

String datastr = "";
   reader = new BufferedReader( new FileReader("C:/Path"+filename));
    String line = reader.readLine();
    while( line != null) {
        datastr += line + "\n";
        line = reader.readLine();
    }
任何帮助都将不胜感激。提前感谢

简单地说,ClassLoader就是答案:

ClassLoader cl = Thread.currentThread().getContextClassLoader(); URL rsc = cl.getResource("MyFile.txt"); File f = new File(rsc.getPath());
但这里有更多关于这个问题的答案,只是为了快速搜索。使用搜索-

所以我就这样做了。。。字符串datastr=;ClassLoader cl=Thread.currentThread.getContextClassLoader;URL rsc=cl.getResourcefile;FileReader f=new FileReaderrsc.getPath;读卡器=新的BufferedReaderf;字符串行=reader.readLine;在线时!=null{datastr+=line+\n;line=reader.readLine;}并收到java.lang.NullPointerException…@pmpc使用调试器找出在哪一步获得NPE。文件变量中有什么?