File Writing failed with java.io.FileNotFoundException: - java

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.

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.

Related

Files getting created with old file details in Java

I am trying to create a simple program which checks if a file was created older than today and delete that file to create a new one . But the creatNewFile method is recreating the file with the old (deleted) files properties . For example the new file also has a creation date of yesterday .
What am i doing wrong here ?
private File createFile() {
logger.trace("Entering createFile method ");
File trackerFile = new File("tracker.txt");
if (!trackerFile.exists()) {
try {
logger.debug("File does not exist . New file being created ");
trackerFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String dateCreated = df.format(this.getCreationTime(trackerFile).toMillis());
logger.debug("File exists file creation time is {}" , dateCreated);
Calendar currCalendar = Calendar.getInstance();
Calendar fileCreateCalendar = Calendar.getInstance();
fileCreateCalendar.setTime(df.parse(dateCreated));
if (currCalendar.get(Calendar.DAY_OF_MONTH) > fileCreateCalendar.get(Calendar.DAY_OF_MONTH)) {
logger.debug("File exists file not created today , being deleted");
trackerFile.delete();
trackerFile.createNewFile();
}
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
logger.trace("Exiting createFile method ");
return trackerFile;
}
Please check out this simple code snippet .. the file is created , deleted and then recreated . The file created at the end has a creation date which is the same as the first file that was deleted . How does this happen ?
public class CreateTempFile {
public static void main(String[] args) {
try {
File file = new File("test.txt");
file.createNewFile();
file.delete();
File newFile = new File("test.txt");
newFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I would suggest you to use similar code to get date / time in order to be sure that you are retrieving the right value (e.g. creation is not modification etc):
Path file = "tracker.txt";
BasicFileAttributes fileAttributes = Files.readAttributes(file, BasicFileAttributes.class);
System.out.println("creationTime: " + fileAttributes.creationTime());
System.out.println("lastAccessTime: " + fileAttributes.lastAccessTime());
System.out.println("lastModifiedTime: " + fileAttributes.lastModifiedTime());
You can find more details in the reference here:
https://docs.oracle.com/javase/tutorial/essential/io/fileAttr.html
I found the answer in an older post , the link is given below .
After deleting file and re-creating file, not change creation date in windows

Create directory in Java but don't throw error if it already exists [duplicate]

The condition is if the directory exists it has to create files in that specific directory without creating a new directory.
The below code only creates a file with the new directory but not for the existing directory . For example the directory name would be like "GETDIRECTION":
String PATH = "/remote/dir/server/";
String fileName = PATH.append(id).concat(getTimeStamp()).append(".txt");
String directoryName = PATH.append(this.getClassName());
File file = new File(String.valueOf(fileName));
File directory = new File(String.valueOf(directoryName));
if (!directory.exists()) {
directory.mkdir();
if (!file.exists() && !checkEnoughDiskSpace()) {
file.getParentFile().mkdir();
file.createNewFile();
}
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(value);
bw.close();
Java 8+ version:
Files.createDirectories(Paths.get("/Your/Path/Here"));
The Files.createDirectories() creates a new directory and parent directories that do not exist. This method does not throw an exception if the directory already exists.
This code checks for the existence of the directory first and creates it if not, and creates the file afterwards. Please note that I couldn't verify some of your method calls as I don't have your complete code, so I'm assuming the calls to things like getTimeStamp() and getClassName() will work. You should also do something with the possible IOException that can be thrown when using any of the java.io.* classes - either your function that writes the files should throw this exception (and it be handled elsewhere), or you should do it in the method directly. Also, I assumed that id is of type String - I don't know as your code doesn't explicitly define it. If it is something else like an int, you should probably cast it to a String before using it in the fileName as I have done here.
Also, I replaced your append calls with concat or + as I saw appropriate.
public void writeFile(String value){
String PATH = "/remote/dir/server/";
String directoryName = PATH.concat(this.getClassName());
String fileName = id + getTimeStamp() + ".txt";
File directory = new File(directoryName);
if (! directory.exists()){
directory.mkdir();
// If you require it to make the entire directory path including parents,
// use directory.mkdirs(); here instead.
}
File file = new File(directoryName + "/" + fileName);
try{
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(value);
bw.close();
}
catch (IOException e){
e.printStackTrace();
System.exit(-1);
}
}
You should probably not use bare path names like this if you want to run the code on Microsoft Windows - I'm not sure what it will do with the / in the filenames. For full portability, you should probably use something like File.separator to construct your paths.
Edit: According to a comment by JosefScript below, it's not necessary to test for directory existence. The directory.mkdir() call will return true if it created a directory, and false if it didn't, including the case when the directory already existed.
Trying to make this as short and simple as possible. Creates directory if it doesn't exist, and then returns the desired file:
/** Creates parent directories if necessary. Then returns file */
private static File fileWithDirectoryAssurance(String directory, String filename) {
File dir = new File(directory);
if (!dir.exists()) dir.mkdirs();
return new File(directory + "/" + filename);
}
I would suggest the following for Java8+.
/**
* Creates a File if the file does not exist, or returns a
* reference to the File if it already exists.
*/
public File createOrRetrieve(final String target) throws IOException {
final File answer;
Path path = Paths.get(target);
Path parent = path.getParent();
if(parent != null && Files.notExists(parent)) {
Files.createDirectories(path);
}
if(Files.notExists(path)) {
LOG.info("Target file \"" + target + "\" will be created.");
answer = Files.createFile(path).toFile();
} else {
LOG.info("Target file \"" + target + "\" will be retrieved.");
answer = path.toFile();
}
return answer;
}
Edit: Updated to fix bug as indicated by #Cataclysm and #Marcono1234. Thx guys:)
code:
// Create Directory if not exist then Copy a file.
public static void copyFile_Directory(String origin, String destDir, String destination) throws IOException {
Path FROM = Paths.get(origin);
Path TO = Paths.get(destination);
File directory = new File(String.valueOf(destDir));
if (!directory.exists()) {
directory.mkdir();
}
//overwrite the destination file if it exists, and copy
// the file attributes, including the rwx permissions
CopyOption[] options = new CopyOption[]{
StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES
};
Files.copy(FROM, TO, options);
}
Simple Solution using using java.nio.Path
public static Path createFileWithDir(String directory, String filename) {
File dir = new File(directory);
if (!dir.exists()) dir.mkdirs();
return Paths.get(directory + File.separatorChar + filename);
}
If you create a web based application, the better solution is to check the directory exists or not then create the file if not exist. If exists, recreate again.
private File createFile(String path, String fileName) throws IOException {
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(".").getFile() + path + fileName);
// Lets create the directory
try {
file.getParentFile().mkdir();
} catch (Exception err){
System.out.println("ERROR (Directory Create)" + err.getMessage());
}
// Lets create the file if we have credential
try {
file.createNewFile();
} catch (Exception err){
System.out.println("ERROR (File Create)" + err.getMessage());
}
return file;
}
A simple solution using Java 8
public void init(String multipartLocation) throws IOException {
File storageDirectory = new File(multipartLocation);
if (!storageDirectory.exists()) {
if (!storageDirectory.mkdir()) {
throw new IOException("Error creating directory.");
}
}
}
If you're using Java 8 or above, then Files.createDirectories() method works the best.

Create whole path automatically when writing to a new file with sub folders [duplicate]

This question already has answers here:
To create a new directory and a file within it using Java
(2 answers)
Closed 4 years ago.
I want to write a new file inside a folder that currently does not exist.
I use it like this:
File file = new File("C:\\user\\Desktop\\dir1\\dir2\\filename.txt");
file.getParentFile().mkdirs();
FileWriter writer = new FileWriter(file);
I get the file filename.txt under a folder called dir1.dir2.
I need dir1/dir2:
How can I achieve this?
Please do not mark this question as duplicate because I didn't get what I need after a reseach.
UPDATE 1
I am using Jasper Report with Spring Boot to export a pdf file.
I need to create the file under a directory name the current year. Under this folder, I need to create a directory called the current month, and under this directory the pdf file should be exported. Example :
(2018/auguest/report.pdf )
I am using LocalDateTime to get year and month
Here is a portion of my code :
ReportFiller reportFiller = context.getBean(ReportFiller.class);
reportFiller.setReportFileName("quai.jrxml");
reportFiller.compileReport();
reportFiller = context.getBean(ReportFiller.class);
reportFiller.fillReport();
ReportExporter simpleExporter = context.getBean(ReportExporter.class);
simpleExporter.setJasperPrint(reportFiller.getJasperPrint());
LocalDateTime localDateTime = LocalDateTime.now();
String dirName = simpleExporter.getPathToSaveFile() + "/"+
localDateTime.getYear() + "/" + localDateTime.getMonth().name();
File dir = new File(dirName);
dir.mkdirs();
String fileName = dirName + "/quaiReport.pdf";
simpleExporter.exportToPdf(fileName, "");
Here is what I get :
Try below code which will work as per your expectation
File dir = new File("C:\\Users\\username\\Desktop\\dir1\\dir2");
dir.mkdirs();
File file = new File(dir, "filename.txt");
FileWriter newFile = new FileWriter(file);
You need to create folder structure first and file next
You need to create directory first then create file:
Like this:
String dirName = "/" + localDateTime.getYear() + "/" + localDateTime.getMonth().name();
File file = new File(dirName);
file.mkdirs();
file = new File(file.getAbsolutePath()+"/quriReport.pdf");
file.createNewFile();
If you go your project directory you see 2018/August/quriReport.pdf
But IDE show subfolder with . if there is only one subfolder.
At first, create the directories, then create a new file to write.
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
class TestDir {
public static void main(String[] args) {
String dirPath = "C:\\user\\Desktop\\dir1\\dir2\\";
String fileName = "filename.txt";
Path path = Paths.get(dirPath);
if(!Files.exists(path)) {
try {
Files.createDirectories(path);
} catch (IOException e) {
e.printStackTrace();
}
}
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(dirPath + fileName), "utf-8"))) {
writer.write("something");
} catch (IOException e) {
e.printStackTrace();
}
}
}
File file = new File("C:\\user\\Desktop\\dir1\\dir2\\filename.txt");
Files.createDirectories(file.getParentFile().toPath());
FileWriter writer = new FileWriter(file);
writer.write("jora");
writer.close();

Reading/Writing to Properties Files inside the jar file

So i am getting back into writing Java after 4 years so please forgive any "rookie" mistakes.
I need to have a properties file where i can store some simple data for my application. The app data itself won't reside here but i will be storing info such as the file path to the last used data store, other settings, etc.
I managed to connect to the properties file which exists inside the same package as the class file attempting to connect to it and i can read the file but i am having trouble writing back to the file. I am pretty sure that my code works (at least it's not throwing any errors) but the change isn't reflected in the file itself after the app is run in Netbeans.
In the above image you can see the mainProperties.properties file in question and the class attempting to call it (prefManagement.java). So with that in mind here is my code to load the file:
Properties mainFile = new Properties();
try {
mainFile.load(prefManagement.class.getClass().getResourceAsStream("/numberAdditionUI/mainProperties.properties"));
} catch (IOException a) {
System.out.println("Couldn't find/load file!");
}
This works and i can check and confirm the one existing key (defaultXMLPath).
My code to add to this file is:
String confirmKey = "defaultXMLPath2";
String propKey = mainFile.getProperty(confirmKey);
if (propKey == null) {
// Key is not present so enter the key into the properties file
mainFile.setProperty(confirmKey, "testtest");
try{
FileOutputStream fos = new FileOutputStream("mainProperties.properties");
mainFile.store(fos, "testtest3");
fos.flush();
}catch(FileNotFoundException e ){
System.out.println("Couldn't find/load file3!");
}catch(IOException b){
System.out.println("Couldn't find/load file4!");
}
} else {
// Throw error saying key already exists
System.out.println("Key " + confirmKey + " already exists.");
}
As i mentioned above, everything runs without any errors and i can play around with trying to add the existing key and it throws the expected error. But when trying to add a new key/value pair it doesn't show up in the properties file afterwords. Why?
You should not be trying to write to "files" that exist inside of the jar file. Actually, technically, jar files don't hold files but rather they hold "resources", and for practical purposes, they are read-only. If you need to read and write to a properties file, it should be outside of the jar.
Your code writes to a local file mainProperties.properties the properties.
After you run your part of code, there you will find that a file mainProperties.properties has been created locally.
FileOutputStream fos = new FileOutputStream("mainProperties.properties");
Could order not to confuse the two files you specify the local file to another name. e.g. mainAppProp.properties .
Read the complete contents of the resource mainProperties.properties.
Write all the necessary properties to the local file mainAppProp.properties.
FileOutputStream fos = new FileOutputStream("mainAppProp.properties");
switch if file exists to your local file , if not create the file mainAppProp.properties and write all properties to it.
Test if file mainAppProp.properties exists locally.
Read the properties into a new "probs" variable.
Use only this file from now on.
Under no circumstances you can write the properties back into the .jar file.
Test it like
[...]
if (propKey == null) {
// Key is not present so enter the key into the properties file
mainFile.setProperty(confirmKey, "testtest");
[...]
Reader reader = null;
try
{
reader = new FileReader( "mainAppProp.properties" );
Properties prop2 = new Properties();
prop2.load( reader );
prop2.list( System.out );
}
catch ( IOException e )
{
e.printStackTrace();
}
finally
{
if (reader != null) {
reader.close();
}
}
}
[...]
}
output : with prop2.list( System.out );
-- listing properties --
defaultXMLPath2=testtest
content of the file mainAppProp.properties
#testtest3
#Mon Jul 14 14:33:20 BRT 2014
defaultXMLPath2=testtest
Challenge:
Read the Property file location in jar file
Read the Property file
Write the variable as system variables
public static void loadJarCongFile(Class Utilclass )
{
try{
String path= Utilclass.getResource("").getPath();
path=path.substring(6,path.length()-1);
path=path.split("!")[0];
System.out.println(path);
JarFile jarFile = new JarFile(path);
final Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
final JarEntry entry = entries.nextElement();
if (entry.getName().contains(".properties")) {
System.out.println("Jar File Property File: " + entry.getName());
JarEntry fileEntry = jarFile.getJarEntry(entry.getName());
InputStream input = jarFile.getInputStream(fileEntry);
setSystemvariable(input);
InputStreamReader isr = new InputStreamReader(input);
BufferedReader reader = new BufferedReader(isr);
String line;
while ((line = reader.readLine()) != null) {
System.out.println("Jar file"+line);
}
reader.close();
}
}
}
catch (Exception e)
{
System.out.println("Jar file reading Error");
}
}
public static void setSystemvariable(InputStream input)
{
Properties tmp1 = new Properties();
try {
tmp1.load(input);
for (Object element : tmp1.keySet()) {
System.setProperty(element.toString().trim(),
tmp1.getProperty(element.toString().trim()).trim());
}
} catch (IOException e) {
System.out.println("setSystemvariable method failure");
}
}

Trying to create file without succes - file appears elsewhere?

I tried to create 3 empty files in my home directory, using this:
this.mainpath = System.getenv("HOME"+"/");
this.single = new File(mainpath + "sin.r");
this.complete = new File (mainpath + "com.r");
this.ward = new File (mainpath+"w.r");
I was unter the impression that this would give me the files desired. However, if I search my home directory, or any other directory, for this files, none of them exists. What am I doing wrong?
Edit: I just find out: I do get a file, but not in my home directory, but the path to it would be /home/myname/NetBeansProjects/myorojectname/nullsin.r.
However, I specifically wanted to create the file in my home!
Well, my code now reads:
this.mainpath = System.getenv("user.home");
this.mainpath = this.mainpath + "/";
this.single = new File(mainpath + "sin.r");
this.single.createNewFile();
System.out.println(this.single.getAbsolutePath());
this.complete = new File (mainpath + "comp.r");
this.complete.createNewFile();
this.ward = new File (mainpath+"w.r");
this.ward.createNewFile();
The "success" of this, however, is that I get an IOException at the first createNeWFile(): File not found.
as for my code how I tried to write sth into those file, there it is:
FileWriter writer1 = null;
FileWriter writer2 = null;
FileWriter writer3 = null;
try {
writer1 = new FileWriter(single);
writer2 = new FileWriter(complete);
writer3 = new FileWriter(ward);
writer1.write("x = cbind(1,2,3)");
writer2.write("x = cbind(1,2,3)");
writer3.write("x = cbind(1,2,3)");
writer1.flush();
writer2.flush();
writer3.flush();
} catch (IOException ex) {
System.out.println(ex.getStackTrace());
} finally {
try {
writer1.close();
writer2.close();
writer3.close();
} catch (IOException ex) {
System.out.println(ex.getStackTrace());
}
You need to use getProperty() instead
System.getProperty("user.home");
Also, the / should be appended after getting the directory path.
this.mainpath = System.getProperty("user.home");
this.single = new File(mainpath + "/sin.r");
this.complete = new File (mainpath + "/com.r");
this.ward = new File (mainpath+"/w.r");
You can call the "createNewFile"-method for each of the objects you've declared to actually create them.

Categories