I have a method that returns a TreeMap and trying to write the content from that TreeMap into a file. In Linux, I am trying to create a new file in the dir: /home/sid/AutoFile/ with the current date appended to the file name.
This is what I came up with:
public void createReconFile() throws SQLException, IOException {
Map<String, String> fileInput = new TreeMap<String, String>();
fileInput = getDiffTableCount();
Set<String> countKeys = fileInput.keySet();
Iterator<String> fileInpIter = countKeys.iterator();
Writer output = null;
//creating a file with currentDate
DateFormat df = new SimpleDateFormat("MM/dd/yyyy:HH:mm:ss");
Date today = Calendar.getInstance().getTime();
String reportDate = df.format(today);
System.out.println(reportDate);
try {
File file = new File("/home/sid/AutoFile/" + "count" + reportDate);
output = new BufferedWriter(new FileWriter(file));
System.out.println("Created new file");
while(fileInpIter.hasNext()) {
String tableName = fileInpIter.next();
String cdp = fileInput.get(tableName);
output.write(tableName +" " + cdp+"\n");
}
} catch(IOException e) {
System.out.println("File Writing failed");
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
} finally {
System.out.println("Closing the file...");
output.close();
}
}
But it ends with the exception:
03/23/2018:05:35:30
File Writing failed
java.io.FileNotFoundException: /home/sid/AutoFile/count03/23/2018:05:35:30 (No such file or directory)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(FileOutputStream.java:270)
at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
at java.io.FileOutputStream.<init>(FileOutputStream.java:162)
The dir: /home/sid/AutoFile/count03/23/2018:05:35:30 is already there and I am trying to create a new file every time that method invokes.
Could anyone let me know what is the mistake I am doing here and how can I create a file properly using java.
SimpleDateFormatclass. It is not only long outdated (along withDateandCalendar), it is also notoriously troublesome. Today we have so much better injava.time, the modern Java date and time API.