Reputation: 1659
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();
}
}
Upvotes: 1
Views: 736
Reputation: 62
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.
Upvotes: 0
Reputation: 5317
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.
Upvotes: 2