Reputation: 2083
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.
Upvotes: 0
Views: 1716
Reputation: 377
Filename in linux cannot have forward slash. So your date format which I believe you want to be used as filename is being taken as directory by linux. You either need to change your date format such that you do not have any forward slash in it or alternatively you can use following line to first create a directory and then write your file in that directory.
new File("/home/ist/" + "count03/23" ).mkdirs();
Also if you already have a directory /home/sid/AutoFile/count03/23/2018:05:35:30 then you cannot have a file with the same name at the same location in linux.
Upvotes: 4