Java-用于读取文本文件的FilenotfoundException [英] Java - FilenotfoundException for reading text file

查看:77
本文介绍了Java-用于读取文本文件的FilenotfoundException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行此命令...

File file = new File("Highscores.scr");

我一直遇到这个错误,而且我真的不知道该如何解决. 该文件当前与我的.java文件位于我的源包中. 通过指定路径,我可以很容易地读取文件,但是我打算在多台计算机上运行此文件,因此我需要文件可随程序一起移植. 这个问题不是关于读取文本文件,而是指定其位置而不使用绝对路径. 香港专业教育学院寻找答案,但我得到的答案只是指定名称"和指定绝对路径". ID张贴图像,使其更清晰,但我没有10代表这样做:/ 我该怎么做?

i keep getting this error, and i really don't know how to get around it. the file is currently sitting in my source packages with my .java files. I can quite easily read the file by specifying the path but i intend to run this on multiple computers so i need the file to be portable with the program. this question isnt about reading the text file but rather specifying its location without using an absolute path . ive searched for the answer but the answers i get are just "specify the name" and "specify the absolute path". id post an image to make it more clear but i dont have the 10 rep to do so :/ how do i do this?

欢呼.

推荐答案

最好的方法是将其放在您的类路径中,然后

The best way to do this is to put it in your classpath then getResource()

package com.sandbox;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;

public class Sandbox {

    public static void main(String[] args) throws URISyntaxException, IOException {
        new Sandbox().run();
    }

    private void run() throws URISyntaxException, IOException {
        URL resource = Sandbox.class.getResource("/my.txt");
        File file = new File(resource.toURI());
        String s = FileUtils.readFileToString(file);
        System.out.println(s);
    }


}

我这样做是因为我假设您需要一个File.但是,如果您有使用InputStream代替的api,则最好使用getResourceAsStream代替.

I'm doing this because I'm assuming you need a File. But if you have an api which takes an InputStream instead, it's probably better to use getResourceAsStream instead.

注意路径,/my.txt.这意味着,获取一个名为my.txt的文件,该文件位于类路径的根目录中".我相信您可以阅读有关getResourcegetResourceAsStream的更多信息,以了解有关如何执行此操作的更多信息.但是这里的关键是,文件的类路径对于您提供可执行文件的任何计算机都是相同的(只要您不在类路径中移动文件).

Notice the path, /my.txt. That means, "get a file named my.txt that is in the root directory of the classpath". I'm sure you can read more about getResource and getResourceAsStream to learn more about how to do this. But the key thing here is that the classpath for the file will be the same for any computer you give the executable to (as long as you don't move the file around in your classpath).

顺便说一句,如果在执行new File的行上出现空指针异常,则意味着您没有为文件指定正确的类路径.

BTW, if you get a null pointer exception on the line that does new File, that means that you haven't specified the correct classpath for the file.

这篇关于Java-用于读取文本文件的FilenotfoundException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆