2016-06-11 410 views
0

我尝试将文本文件中的每行存储到数组中时遇到问题。到目前为止,我的程序只能读取文件。这是我到目前为止。将文本文件中的每行存储到数组中

public class assignment1 { 

    public static void main(String[] args) { 
     System.out.println(System.getProperty("user.dir")); 
     File fileName = new File("competitors.txt"); 
     try { 
      Scanner scnr = new Scanner(fileName); 
     } catch (Exception e) { 
      System.out.println(e); 
     } 
    } 
} 
+0

你可能想看看这个的其他问题http://stackoverflow.com/a/12857731/6383857 – StaticBeagle

回答

0

你可以遍历所有的Scanner,直到它有没有更多的行:

List<String> list = new LinkedList<>(); 
try (Scanner scanner = new Scanner(fileName)) { 
    while (scanner.hasNextLine()) { 
     list.add(scanner.nextLine()); 
    } 
} catch (FileNotFoundException e) { 
    System.out.println(e); 
} 
String[] array = list.toArray(new String[list.size()]); 
+0

@ D.尼克你应该提供正确的完整路径 – Mureinik

相关问题