String[][] EmployeeArray = new String [1000][25];
this is my array, it has all the info I need in it already but I want to send all the data from here into an text file called EmployeeFile. How should I do this?
String[][] EmployeeArray = new String [1000][25];
this is my array, it has all the info I need in it already but I want to send all the data from here into an text file called EmployeeFile. How should I do this?
You can Serialize it, or even better do some json decorations/formatting and then write that to a file...
jusing json could be as simple as:
String[][] x = { { "0-0", "0-1", "0-2" }, { "1-0", "1-1", "1-2" }, { "2-0", "2-1, "2-2" } };
try (Writer writer = new FileWriter("my2DArray.json")) {
Gson gson = new GsonBuilder().create();
gson.toJson(x, writer);
}
First of all you will need to loop over your array and create a single string containing your data to be written to the file. This is done so you can add the new line characters where you want them.
String fileContents = new String();
for(int i=0; i<1000; i++) {
for(int j=0; j<25; j++) {
fileContents += EmployeeArray[i][j]
}
fileContents += "\n";
}
The code above is very basic and it is ment to demonstrate the basic idea. It would be more efficient to use a StringBuilder and I guess there are 100 ways to improve those lines further.
Then you can use the following method to write to the file:
public boolean writeFile(String data, String path) {
try {
byte[] encoded = data.getBytes(StandardCharsets.UTF_8);
java.nio.file.Files.write(Paths.get(path),
encoded, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
return true;
} catch(IOException e) {
e.printStackTrace();
}
return false;
}
You should be careful with the options StandardOpenOption.CREATE and StandardOpenOption.TRUNCATE_EXISTING. They will overwrite existing files. Somtimes you need to append to the file, adjust accordingly.
The StandardOpenOption documentation can be found here. StandardOperation.APPEND comes in handy for logging purposes.
Also note that the character set used is UTF8. It is generally a good idea to use UTF8 if it covers your needs. If you get strange characters in your data you might need to also adjust accordingly.