简体   繁体   中英

How could i get a chars from a text file and put it into a 2D array?

for example:

-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-
  1. Read text file line by line
  2. Split string by - so you will have char array add it in your 2d char array.

The easiest way would be to use the toCharArray() method of String.

So if you are using a 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();
   }

char[] firsDimension is not 2d. Try something like,

    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();
    }

With scanner class

    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();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM