当我尝试添加到数组列表时找不到文件

我试图添加到数组列表,但 eclipse 无法找到 .txt 文件

public void readData(String filename) {
 
    try{
        File file = new File("C:\\Users\\Where Are Yew\\eclipse-workspace\\A2\\bin\\input.txt");
        FileReader filereader = new FileReader(file);
        BufferedReader br=new BufferedReader(filereader);
        String line;
        while(true) {
           line=br.readLine();
           if(line==null)
               break;
           String[] words=line.split("\\s");    
sunlei890325sunlei 回答:当我尝试添加到数组列表时找不到文件

使用此方法的更合适的方法可能是执行以下操作:

public void readData(String filename) {
    // 'Try With Resources' is use here to auto-close reader. 
    try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
        String line;
        while((line = br.readLine()) != null) {
            line = line.trim();  // Trim leading/trailing whitespaces,etc.
            // Skip past blank data lines
            if (line.isEmpty()) {
                continue;
            }
            // Do whatever you want to do with the read in data line.
            String[] words = line.split("\\s+");    
        }
    }
    /* Catch and display any IO Exception. If the file 
       can't be found then this will tell you. Perhaps
       you don't have permission to access it... it 
       would tell you that too. Don't ignore Exceptions. */
    catch (IOException ex) {
        Logger.getLogger("readData() Method Error!").log(Level.SEVERE,null,ex);
    }
}
,
 String[] words = line.split("\\s+");

是您需要的,因为您的输入文件包含不规则间距。我强烈建议您使用制表符分隔的文件而不是空格分隔的文件,因为您的字段可以在需要的地方使用空格

本文链接:https://www.f2er.com/11538.html

大家都在问