简体   繁体   中英

how to write 2D char array into a file

How do I write a 2D char array to a file. I searched for the solution everywhere, but didn't find an answer.

void printDATA(){
String[][] stringArray = Arrays.copyOf(data, data.length, String[][].class);
char[][] charArray = new char[stringArray.length][stringArray[0].length];
            for(int i = 0; i < stringArray.length; i++)
            {
                for(int j = 0; j < stringArray[0].length; j++)
                {
                    charArray[i][j] = stringArray[i][j].charAt(0);
                }
            }
        File file = new File("result.doc");
        try {
            //FileWriter fout = new FileWriter(file);//Gives error
            PrintWriter fout = new PrintWriter(file);//This also gives error
            fout.write(charArray);
            fout.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

The Writer API does not support writing arrays of arrays. Only int (which should really be a char ), String , or char[] . Loop over the arrays to write.

for (int i = 0; i < charArray.length; i++) {
    fout.write(charArray[i]);
}

You will probably want to throw in newline characters as well.

Pseudo-code:

for(int i =0;i< 1st dimension; i++)
   { for(int j =0;j< 2nd dimension; j++)
        {
          write (array[i][j])
          write (some symbol)
        }
  write (some other symbol)
   }

Then you will need to remember the delimiting symbols when you want to read from the file.

Then you will need to read the whole file as String and split it using the 1st symbol then the 2nd symbol.

For example, lets take the following 2D array:

apple orange pineapple.

banana tomato grape.

You can write it to a file as 1D string as: apple,orange,pineapple;banana,tomato,grape;

Then when you read the file as string, you split on ";" and get: apple,orange,pineapple banana,tomato,grape

then split each one at "," and re-build your 2D array.

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