java FileInputStream 找不到文件
Posted
技术标签:
【中文标题】java FileInputStream 找不到文件【英文标题】:java FileInputStream cannot find file 【发布时间】:2014-06-06 03:49:30 【问题描述】:我对 Java 编码非常陌生,但遇到了很多困难。 我想使用从文件中读取的缓冲读取器编写一个程序,我已经创建了一个名为“scores.txt”的文件。 所以我有一个名为 processFile 的方法,它假设设置 BufferedReader 并遍历文件,读取每个分数。然后,我需要将分数转换为整数,将它们相加,并显示计算出的平均值。
我不知道如何将它们相加并计算平均值,但我目前正在从文件中读取数据。 它一直说它无法处理文件,但我确定我的文档中有一个名为“scores.txt”的文件。
这是我目前所拥有的......这很糟糕。我只是不太擅长这个:(也许有不同的问题?
public static void main(String[] args) throws IOException,
FileNotFoundException
String file = "scores.txt";
processFile("scores.txt");
//calls method processFile
public static void processFile (String file)
throws IOException, FileNotFoundException
String line;
//lines is declared as a string
BufferedReader inputReader =
new BufferedReader (new InputStreamReader
(new FileInputStream(file)));
while (( line = inputReader.readLine()) != null)
System.out.println(line);
inputReader.close();
【问题讨论】:
使用Files.newBufferedReader()
开头 -- 以及 try-with-resources 语句
您缺少文件的路径。现在你只有文件名。
【参考方案1】:
有两个主要选项可供选择
使用文件的绝对路径(在 Windows 中从驱动器号开始或 *.nix 中的斜杠)。 “仅用于测试”任务非常方便。
示例 Windows - D:/someFolder/scores.txt, *.nix - /someFolder/scores.txt
把文件放到项目根目录下,这样就可以看到了 到类加载器。
【讨论】:
【参考方案2】:将 score.txt 放在项目文件夹的根目录中,或将文件的完整路径放在 String file
中。
程序不会知道检查您的“我的文档”文件夹中的scores.txt
【讨论】:
【参考方案3】:如果您使用 IntelliJ,请在您的包中创建一个 input.txt 文件,然后右键单击 input.txt 文件并单击 copy path
。您现在可以将该路径用作输入参数。
例子:
in = new FileInputStream("C:\\Users\\mda21185\\IdeaProjects\\TutorialsPointJava\\src\\com\\tutorialspoint\\java\\input.txt");
【讨论】:
【参考方案4】:如果您在 Eclipse 中,则从本地系统获取绝对路径,然后右键单击该文件并单击属性,您将获得路径复制它并将其放在下面这对我有用在 maven 项目中保留属性文件在 src/main/resources `
私有静态属性 properties = new Properties();
public Properties simpleload()
String filepath="C:/Users/shashi_kailash/OneDrive/L3/JAVA/TZA/NewAccount/AccountConnector/AccountConnector-DEfgvf/src/main/resources/sample.properties";
try(FileInputStream fis = new FileInputStream(filepath);)
//lastModi = propFl.lastModified();
properties.load(fis);
catch (Exception e)
System.out.println("Error loading the properties file : sample.properties");
e.printStackTrace();
return properties;
`
【讨论】:
以上是关于java FileInputStream 找不到文件的主要内容,如果未能解决你的问题,请参考以下文章
java读取文件,报找不到文件错误,我写的路径跟报错的路径不一样,怎么回事?