Java 传递文件到方法错误?

Java Passing a file to a method error?

你好,我目前正在为我的编程课程做作业,我需要将文件传递给另一个方法,但是,我不断收到错误消息:

"Exception in thread "main" java.io.FileNotFoundException: USPopulation.txt (系统找不到指定的文件)"

而且我不确定我哪里出错了,我尝试了更具体的文件路径,但没有用。

这是我的工作,如果有人能告诉我我做错了什么,那就太好了:)(也忽略 ArrayList 版本,我还没到那儿。):

import java.util.Scanner;
import java.io.*;

public class populationsArrays 
{

   public static void main(String[] args) throws IOException 
   {
       // Array Version
       ArrayVersion();
       System.out.println("Finished Array Version of Assignment");

       // ArrayList Version
       ArrayListVersion();
       System.out.println("Finshed ArrayList Version of Assignment");
   }

   // Method for ArrayVersion
   public static void ArrayVersion() throws IOException
   {


       // Array to use for Population data
       int[] population =  new int[39];

       // Call the method to get data into array
       population = getDataFromFile("USPopulation.txt");


       if(population == null)
       {
           System.out.println("Error: Population did not load");
           return;
       }


   }

   // Method to get data from specified "filename" into an array of ints
   public static int[] getDataFromFile(String USPopulation) throws IOException
   {
       final int SIZE = 39;
       // Array to use for Population data
       int[] population =  new int[SIZE];
       int i = 0;
       // Opening file
       File file = new File("USPopulation.txt");
       Scanner inputFile = new Scanner(file);

       while(inputFile.hasNext() && i < population.length)
       {
           population[i] = inputFile.nextInt();
           i++;
       }


       inputFile.close();

       return population;
   }

   // Method for ArrayListVersion
   public static void ArrayListVersion() throws IOException
   {

   }
}

错误信息:

Exception in thread "main" java.io.FileNotFoundException: USPopulation.txt (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.util.Scanner.<init>(Scanner.java:611)
at populationsArrays.getDataFromFile(populationsArrays.java:48)
at populationsArrays.ArrayVersion(populationsArrays.java:27)
at populationsArrays.main(populationsArrays.java:10)

编辑:我尝试将文件名更改为 getDataFromFile 和新文件的文件路径,但是 none 有效

编辑:我正在使用 Windows 10,我必须使用文件

最后编辑:我终于让它工作了,我在桌面上的不同位置开始了一个新的项目文件,并将 USPopulation 文件保存在与新项目文件相同的文件夹中,并粘贴了我的工作并做了 Hunt写了。非常感谢!

由于您没有向路径提供文件,因此它假定它位于您的当前工​​作目录 (CWD) 中。您的 CWD 将是您开始程序的地方。您可以调用 System.out.println(file.getPath()) 来验证是否在您的 CWD 中搜索了该文件,正如 ug_ 所建议的那样。

如果它不在您的 CWD 中,您可以像这样给出文件路径的绝对位置(如果在 Windows 上):

getDataFromFile("C:\Users\USER\Desktop\USPopulation.txt");

您必须通过在其前面放置另一个 \ 来转义 \。

与其只写文件名,不如尝试给出完整的文件路径和文件名。 例如

//code
File file = new File("C:\Users\HUNT\DocumentsUSPopulation.txt");

这肯定有用。

并为方法 getdatafromfile("");

提供相同的路径