从.txt文件读取到2d数组

时间:2016-05-07 17:41:46

标签: java

我的txt文件全部用空格分隔,我知道如何读取文件,但我不知道如何将数据放入数组

这是代码:

public static void main(String[] args) throws IOException
{
    ArrayList<String> list=new ArrayList<>();

    try{
            File f = new File("C:\\Users\\Dash\\Desktop\\itemsset.txt");
            FileReader fr = new FileReader(f);
            BufferedReader br = new BufferedReader(fr);
            String line = br.readLine();
            String array[][] = null ;
            try {
                    while ((line = br.readLine()) != null) {

                    }
                    br.close();
                    fr.close(); 
                }
            catch (IOException exception) {
                System.out.println("Erreur lors de la lecture :"+exception.getMessage());
                }   
        }    
    catch (FileNotFoundException exception){
            System.out.println("Le fichier n'a pas été trouvé");
        }
}

以下说明:

2 个答案:

答案 0 :(得分:1)

  

我的txt文件全部用空格分隔

读取每一行,并用空格分割。首先,您可以使用user.home系统属性和相对路径构建文件路径。像,

File desktop = new File(System.getProperty("user.home"), "Desktop");
File f = new File(desktop, "itemsset.txt");

然后使用try-with-resources并将每行读入List<String[]>之类的

List<String[]> al = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(f))) {
    String line;
    while ((line = br.readLine()) != null) {
        al.add(line.split("\\s+"));
    }
} catch (IOException exception) {
    System.out.println("Exception: " + exception.getMessage());
    exception.printStackTrace();
}

然后,您可以将List<String[]>转换为String[][],然后将其显示为Arrays.deepToString(Object[])

String[][] array = al.toArray(new String[][] {});
System.out.println(Arrays.deepToString(array));

答案 1 :(得分:0)

我只是沉迷于Java 8的美丽及其Streams

Path p = Paths.get(System.getProperty("user.home"),"Desktop","itemsset.txt");
String [][] twoDee = Files.lines(p)
    .map((line)->line.trim().split("\\s+"))
    .toArray(String[][]::new);
System.out.println(Arrays.deepToString(twoDee));

可以找到类似的情况:

其他研究 - java: convert a list of array into an array of array