Check if file already exist in the same path - java

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.

Related

Creating temporary file and rename to actual file

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.

checking files as command line arguments in java

I'm trying to pass in a text file(input and output files) as the command line arguments inside a try-catch block.
This is a snippet of the code:
try {
PrintWriter outFile = new PrintWriter(new FileOutputStream(args[0]));
} catch (FileNotFoundException exc) {
System.out.println("file does not exist");
} catch (Exception e) {
System.out.println("general exception");
}
I'm trying to check it by passing a file that doesn't exist but it doesn't seem to work, not even in the general exception. I tried printStream as well but nothing really changed.
Any help would be appreciated, thanks!
First create a file from text
File inputFile = new File(args[0]);
Now check the existence of file using inputFile.exists() which will give you boolean result true if file exists or false if doesn't
Plus you also wanna put a check for directories too because inputFile.exists() also return true if the input Path is of a directory (Folder)
so your check will look like
if(inputFile.exists() && ! inputFile.isDirectory()) // ! mean not/complement operator
{
// yes it's a file
}
Why complement ? cuz we wanna only go further if input represents a file not directory

Using Java's File class and how to gain correct access permissions to create files

bellow is the code of a house cleaning function i have written, the function is supposed to check for a files existance, if it is not there it then creates the file and adds some data to it.
However when i check that i have read and write permisions using the file.canRead() and file.canWrite() these both return false when checked however the program should have access to the file path where specified.
public void HouseCleaning()
{
//inform the user that the file is not available
System.out.println("According the the checks we have run, the current system you are on we do not have the required files set up");
System.out.println("...");
//create info.txt
try
{
File file = new File("C:\\GameCounter\\info.txt");
System.out.println(file.canRead());
System.out.println(file.canWrite());
if(file.canRead() && file.canWrite())
{
//then we can create the file
System.out.println("we can do this");
if(!file.exists())
{
//file does not exist
if(file.createNewFile())
{
//file has been created
System.out.println("File has been successfully created!");
PrintWriter writer = new PrintWriter("C:\\GameCounter\\info.txt", "UTF-8");
writer.println("Info File:");
writer.flush();
writer.close();
}
else
{
//file has not been created!
System.out.println("for some reason the file cannot be created!");
}
}
else
{
//file must already exist? so check for other required ones!
}
}
else
{
System.out.println("we require extre permissions!");
}
}
catch(Exception e)
{
//error has been thrown
System.out.println(e);
}
}
So my question is firstly is that theoretically if the code bellow is correct then it is permissions on the hard disk itself then? if the code is not correct please do correct me.
Many Thanks for any help regarding this.
I suggest you change your program and use the advantages Javas Exception Handling has to offer.
private final static String COUNTER = "C:\\GameCounter\\info.txt";
public static void main(String[] args) {
File file = new File(COUNTER);
if (!file.exists()) {
try {
PrintWriter writer = new PrintWriter(COUNTER, "UTF-8");
writer.println("Info File:");
writer.flush();
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
/// ... more to come
}
This is a lot shorter and you have to take care of the exceptions anyway. If the file can not be written to (In my test I simply created it and assigned the readonly attribute) you will receive an according exception:
java.io.FileNotFoundException: C:\GameCounter\info.txt (Access denied)
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)
at java.io.PrintWriter.<init>(PrintWriter.java:192)
at java.io.PrintWriter.<init>(PrintWriter.java:232)
at xyz.main(xyz.java:12)
In my example I only dump the exception to the screen. In a real life scenario you need to react on the exception and perhaps re-throw a exception you defined on your own.
The methods canRead and canWrite return false if the file does not exist.
Quote from the documentation (canRead):
Returns:
true if and only if the file specified by this abstract pathname exists and can be read by the application; false otherwise
and (canWrite):
Returns:
true if and only if the file system actually contains a file denoted by this abstract pathname and the application is allowed to write to the file; false otherwise.
The reason the file.canRead() file.canWrite() return false are most likely because you have not created the files.
Java Doc
public boolean canRead() Tests whether the application can
read the file denoted by this abstract pathname.
The method calls return true when you create the files first.
Remember, File is a representation of a system file, simply creating an instance of the File object will not create a file

Creating and Writing to a File

if (!file.exists())
file.mkdirs();
file.createNewFile();
The error states that I have a problem with actually 'writing' Go Falcons to the file, it will state that the file access is denied, Does that mean something is wrong with my code?
Error states: FileNotFoundException
Access is denied
PS: how do I actually read this file, once it's writable?
If I understand your question, one approach would be to use a PrintWriter
public static void main(String[] args) {
File outFile = new File(System.getenv("HOME") // <-- or "C:/" for Windows.
+ "/hello.txt");
try {
PrintWriter pw = new PrintWriter(outFile);
pw.println("Go Falcons");
pw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Which creates a single line ascii file in my home folder named "hello.txt".
$ cat hello.txt
Go Falcons
Your problem is that right before you attempt to create your output file, you first create a directory with the same name:
if (!file.exists())
file.mkdirs(); // creates a new directory
file.createNewFile(); // fails to create a new file
Once you've already created the directory, you can no longer create the file, and of course, you cannot open a directory and write data to it as if it were a file, so you get an access denied error.
Just delete the file.mkdirs(); line and your code will work fine:
if (!file.exists())
file.createNewFile(); // creates a new file
Change:
if (!file.exists())
file.mkdirs();
file.createNewFile();
To:
if (!file.exists()) {
file.createNewFile();
}
But first, go read some tutorials or articles. Why are you extending Exception?
You can take the substring of the path till folder structure(excluding file name) and create directories using method mkdirs(). Then create file using createNewFile() method. After that write to newly created file. Don't forget to handle exceptions.

FileNotFoundException when using FileWriter

I am trying to write some message to text file. The text file is in the server path. I am able to read content from that file. But i am unable to write content to that file. I am getting FileNotFoundException: \wastServer\apps\LogPath\message.txt (Access Denied).
Note: File has a read and write permissions.
But where i am doing wrong. Please find my code below.
Code:
String FilePath = "\\\\wastServer\\apps\\LogPath\\message.txt";
try {
File fo = new File(FilePath);
FileWriter fw=new FileWriter(fo);
BufferedWriter bw=new BufferedWriter(fw);
bw.write("Hello World");
bw.flush();
bw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Please help me on this?
Please check whether you can access the apps and LogPath directory.
Type these on Run (Windows Key + R)
\\\\wastServer\\apps\\
\\\\wastServer\\apps\\LogPath\\
And see whether you can access those directories from the machine and user you are executing the above code.
You don't have write access to the share, one of the directories, or the file itself. Possibly the file is already open.
After this line
File fo = new File(FilePath);
try to print the absolute path
System.out.println( fo.getAbsolutePath() );
And then check whether the file exists in that location, instead of directly checking at
\\\\wastServer\\apps\\LogPath\\message.txt
So , you will know, where the compiler is searching for the file.

Categories