扫描仪 - 找不到文件

时间:2014-06-12 02:12:55

标签: java java.util.scanner

我尝试将文本文件加载到java中,但是我在代码中找不到文件时遇到了问题。 我的文件名为' test.txt'并保存在src / test.txt,src / fileIOTest / test.txt和资源文件中,但不管我如何尝试加载文件,程序似乎无法找到它。它显示在包资源管理器中,但会抛出一个未找到文件的异常。

package fileIOTest;

 //This project tests out the scanner system, reading a text file into an array.
import java.io.IOException;
import java.util.Scanner;
import java.io.*;

public class Test {

public void init(){


    Scanner sc = null;
    try {
        sc = new Scanner(new FileReader("/test.txt"));
    } catch(IOException e){
        e.printStackTrace();// print the error
    }

    int[] testArray = new int[10];  

    for(int i = 0; i < 10; i++){
        testArray[i] = sc.nextInt();
        System.out.println(testArray[i]);
        }

    }


public static void main(String[] args){
    Test fileLoader = new Test();
    fileLoader.init();

    }
}

修改:这是我的文件系统Here's my file system

1 个答案:

答案 0 :(得分:0)

好的,试试:

File directory = new File("src/test.txt");
Path file = Paths.get(directory.getAbsolutePath());
Scanner sc = new Scanner(file);

或者:尝试删除斜杠可能有效:

Scanner sc = newScanner(new FileReader("test.txt"));
相关问题