Creating temporary file and rename to actual file - java

I am trying to create a temporary file and then rename it to a usable file. The temp file is getting created in %temp% but not getting renamed:-
static void writeFile() {
try {
File tempFile = File.createTempFile("TEMP_FAILED_MASTER", "");
PrintWriter pw = new PrintWriter(tempFile);
for (String record : new String[] {"a","b"}) {
pw.println(record);
}
pw.flush();
pw.close();
System.out.println(tempFile.getAbsolutePath());
File errFile = new File("C:/bar.txt");
tempFile.renameTo(errFile);
System.out.println(errFile.getAbsolutePath());
System.out.println("Check!");
} catch (Exception e) {
e.printStackTrace();
}
}

There are a few reasons why a rename can fail. The common ones are:
You don't have write permission for the source or destination directory.
The file you are renaming is open (on Windows)
You are attempting to rename across different file systems.
It can be difficult to diagnose these (and other) failure reasons if you are using File.renameTo because all you get is a boolean return value.
I recommend using Files.move instead. It can cope with moving files between file systems, and will throw an exception if the file cannot be renamed.

Related

Check if file already exist in the same path

I want to check if a specific file already exist in the same folder.
If it doesn't exist then create a new file and type in certain thing.
for example. if filePath = test.txt and test.txt doesn't exist.
Create a new file name test.txt and put 12345 in the first line of the file.
Currently my method wont even run this if statement despite the condition is met. (test.txt does not exist)
PrintWriter output;
File file = new File(filePath);
if(!file.isFile()){
try {
output = new PrintWriter(new FileWriter(filePath));
} catch (IOException ex) {
throw new PersistenceException("Error!", ex);
}
output.print("12345");
output.flush();
output.close();
}
You can check whether a file exist or not by creating a File object and using exist method. File objects are different in java compared to C, when you create a File object you do not necessarily create a physical file.
File file = new File(pathString);
if (file.exists())
{
// File already exists
}
else
{
// You can create your new file
}
I think you could use this condition in your if:
Files.exists(Paths.get(file))
You can decide to use the specification NOFOLLOW_LINKS in order to avoid to follow symbolic link.
This will help you to check if the file exists or not.
I hope this could help you.

Directory not showing up in desktop, and file not being created?

The following program has the purpose of creating a directory,
folderforallofmyjavafiles.mkdir();
and making a file to go inside that directory,
File myfile = new File("C:\\Users\\username\\Desktop\\folderforallofmyjavafiles\\test.txt");
There are two problems though. One is that it says the directory is being created at the desktop, but when checking for the directory, it is not there. Also, when creating the file, I get the exception
ERROR: java.io.FileNotFoundException: folderforallofmyjavafiles\test.txt (The system cannot find the path specified)
Please help me resolve these issues, here is the full code:
package mypackage;
import java.io.*;
public class Createwriteaddopenread {
public static void main(String[] args) {
File folderforallofmyjavafiles = new File("C:\\Users\\username\\Desktop");
try {
folderforallofmyjavafiles.mkdir(); //Creates a directory (mkdirs makes a directory)
if (folderforallofmyjavafiles.isDirectory() == true) {
System.out.println("Folder created at " + "'" + folderforallofmyjavafiles.getPath() + "'");
}
} catch (Exception e) {
System.out.println("Not working...?");
}
File myfile = new File("C:\\Users\\username\\Desktop\\folderforallofmyjavafiles\\test.txt");
//I even tried this:
//File myfile = new File("folderforallofmyjavafiles/test.txt");
//write your name and age through the file
try {
PrintWriter output = new PrintWriter(myfile); //Going to write to myfile
//This may throw an exception, so I always need a try catch when writing to a file
output.println("myname");
output.println("myage");
output.close();
System.out.println("File created");
} catch (IOException e) {
System.out.printf("ERROR: %s\n", e); //e is the IOException
}
}
}
Thank you so much for helping me out, I really appreciate it.
:)
You're creating the Desktop folder in the C:\Users\username folder. If you check the return value of mkdir, you'd notice it's false because the folder already exists.
How would the system know that you want a folder named folderforallofmyjavafiles unless you tell it so?
So, you didn't create the folder, and then you try to create a file in the (nonexistent) folder, and Java tells you the folder doesn't exist.
Agreed that it's a bit obscure, using a FileNotFoundException, but the text does say "The system cannot find the path specified".
Update
You're probably confused about the variable name, so let me say this. The following are all the same:
File folderforallofmyjavafiles = new File("C:\\Users\\username\\Desktop");
folderforallofmyjavafiles.mkdir();
File x = new File("C:\\Users\\username\\Desktop");
x.mkdir();
File folderToCreate = new File("C:\\Users\\username\\Desktop");
folderToCreate.mkdir();
File gobbledygook = new File("C:\\Users\\username\\Desktop");
gobbledygook.mkdir();
new File("C:\\Users\\username\\Desktop").mkdir();

Read/Write to a .txt file from JAR

Currently I'm developing a java application to carry out a survey. I want to read/write to a .txt file, creating a .csv to store inputted data. Below is code I have used so far to write data - Of course this makes the JAR file not portable as it has an absolute path.
File file = new File("C:/Files/JavaApp/src/text.text/");
FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter(file, true);
} catch (IOException e) {
System.out.println(e.getMessage());
}
bw = new BufferedWriter(fw);
try {
bw.write("blah" + ",");
} catch (IOException e) {
System.out.println(e.getMessage());
}
try {
bw.newLine();
} catch (IOException e) {
System.out.println(e.getMessage());
}
try {
bw.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
I have tried several methods such as ClassName.class.getResource("Text.text"); but it will always return a Reflection or a NullPointer error.
I know that writing to a file within the JAR does pose some problems, meaning I would have to point to a file outside to read/write. However I don't know how to preform this in code. I need the JAR file to be completely portable. Even if that means it must be kept within a directory, so the JAR can search for the .txt file within that directory. Or, is there another way?
If anyone can help me out, I would be very grateful.
To read from the Jar file: How to read a file from jar in Java?
The file is an archive file. It is a zip file with a .jar extension. You shouldn't be writing to it. If the jar file has been signed (security projected) you cannot write to it. Changing a single bit in the file will invalidate it.
What you should do is store a default file in Jar and load that to the "user.home" folder if it is not already there.

Locate a specific file in a directory by name plus saving a file to the local folder

I would like to locate a file named SAVE.properties. I have looked at different questions that seem like they would answer me, but I can't see that they do.
For example, I would like to check to see whether or not SAVE.properties exists within a directory (and its subfolders).
I would also like to know how I could save a .properties file (and then read it afterwards from this location) to the directory where my program is being run from. If it is run from the desktop, it should save the .properties file there.
Saving properties can easily be achieved through the use of Properties#store(OutputStream, String), this allows you to define where the contents is saved to through the use of an OutputStream.
So you could use...
Properties properties = ...;
//...
try (FileOutputStream os = new FileOutputStream(new File("SAVE.properties"))) {
properties.store(os, "Save");
} catch (IOException exp) {
exp.printStackTrace();
}
You can also use Properties#load(InputStream) to read the contents of a "properties" file.
Take a closer look at Basic I/O for more details.
Locating a File is as simple as using
File file = new File("SAVE.properties");
if (file.exists) {...
This checks the current working directory for the existence of the specified file.
Searching the sub directories is little more involved and will require you to use some recursion, for example...
public File find(File path) {
File save = new File(path, "SAVE.properties");
if (!save.exists()) {
save = null;
File[] dirs = path.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.isDirectory();
}
});
for (File dir : dirs) {
save = find(dir);
if (save != null) {
break;
}
}
}
return save;
}
Using find(new File(".")) will start searching from the current working directory. Just beware, under the right circumstances, this could search your entire hard disk.

Java: Error when save file in Resource after Deployment

My program has a function that read/write file from resource. This function I have tested smoothly.
For example, I write something to file, restart and loading again, I can read that data again.
But after I export to jar file, I faced problems when write file. Here is my code to write file:
URL resourceUrl = getClass().getResource("/resource/data.sav");
File file = new File(resourceUrl.toURI());
FileOutputStream output = new FileOutputStream(file);
ObjectOutputStream writer = new ObjectOutputStream( output);
When this code run, I has notice error in Command Prompt:
So, My data cannot saved. (I know it because after I restarted app, nothing changed !!!)
Please help me solve this problem.
Thanks :)
You simply can't write files into a jar file this way. The URI you get from getResource() isn't a file:/// URI, and it can't be passed to java.io.File's constructor. The only way to write a zip file is by using the classes in java.util.zip that are designed for this purpose, and those classes are designed to let you write entire jar files, not stream data to a single file inside of one. In a real installation, the user may not even have permission to write to the jar file, anyway.
You're going to need to save your data into a real file on the file system, or possibly, if it's small enough, by using the preferences API.
You need to read/write file as an input stream to read from jar file.
public static String getValue(String key)
{
String _value = null;
try
{
InputStream loadedFile = ConfigReader.class.getClassLoader().getResourceAsStream(configFileName);
if(loadedFile == null) throw new Exception("Error: Could not load the file as a stream!");
props.load(loadedFile);
}
catch(Exception ex){
try {
System.out.println(ex.getMessage());
props.load(new FileInputStream(configFileName));
} catch (FileNotFoundException e) {
ExceptionWriter.LogException(e);
} catch (IOException e) {
ExceptionWriter.LogException(e);
}
}
_value = props.getProperty(key);
if(_value == null || _value.equals("")) System.out.println("Null value supplied for key: "+key);
return _value;
}

Categories