我如何从文本文件中获取字符并将其放入2D数组?

时间:2010-12-19 18:31:44

标签: java

例如:

-8-88-8-8-8--8

-8-8-8-8-8-8-8

*-8-8-8-8--8-8

8--8-8-8-8--8-

3 个答案:

答案 0 :(得分:2)

  1. 逐行阅读文本文件
  2. -拆分字符串,这样你就可以将char数组添加到你的2d char数组中。

答案 1 :(得分:2)

最简单的方法是使用String的toCharArray()方法。

因此,如果您使用的是BufferedReader

   ArrayList<String> list = new ArrayList<String>();

   BufferedReader br = new BufferedReader(new FileReader("file"));
   while ((thisLine = br.readLine()) != null) { 
     list.add(thisLine);
   } 

   // finally convert the arraylist to a char[]
   char[] firstDimension = new char[list.size()];
   for (int i = 0; i < list.length; i++) {
       firstDimension[i] = list.get(i).toCharArray();
   }

答案 2 :(得分:0)

char [] firsDimension不是2d。尝试类似的事情,

    try {
        List<String> list = new ArrayList<String>();

        String thisLine = null;
        BufferedReader br;
        br = new BufferedReader(new FileReader("/path/to/file/yourfile.txt"));

        while ((thisLine = br.readLine()) != null) {
            list.add(thisLine);
        }

        char[][] firstDimension = new char[list.size()][];
        for (int i = 0; i < list.size(); i++) {
            firstDimension[i] = list.get(i).toCharArray();
        }

        //print values
        for (int i=0;i<firstDimension.length;i++) {
            for (int j=0;j<firstDimension[i].length;j++) {
                System.out.println(firstDimension[i][j]);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

使用扫描仪类

    try {
        Scanner scanner = new Scanner(new File(
                "/home/sinan/Desktop/yourfile.txt"));
        scanner.useDelimiter(System.getProperty("line.separator"));

        ArrayList<String> list = new ArrayList<String>();

        while (scanner.hasNext()) {
            list.add(scanner.next());
        }
        scanner.close();

        // finally convert the arraylist to a char[][]
        char[][] firstDimension = new char[list.size()][];
        for (int i = 0; i < list.size(); i++) {
            firstDimension[i] = list.get(i).toCharArray();
        }

        for (int i = 0; i < firstDimension.length; i++) {
            for (int j = 0; j < firstDimension[i].length; j++) {
                System.out.println(firstDimension[i][j]);
            }
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }