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.
Related
I just started to work with files today with Android and have been pulling my hair out all day. This throws a FileNotFoundException:
public void writeConfig(){
try {
File file = new File(Environment.getExternalStorageDirectory() + "/" + "AppName", "TimetableConfiguration");
if (!file.mkdirs()) {
P.rint("Couldn't create directory");
}
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(getActivity().getSharedPreferences("periods", MODE_PRIVATE).getString("periods", null).getBytes());
fileOutputStream.close();
} catch (FileNotFoundException e) {
P.rint("Didn't find file");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Any ideas?
I notice that instead of creating a file, it creates a child folder. Why is it doing this?
Thanks for any help :)
FileNotFoundException: Creates child folder instead of file
Yes. That is what you do.
You first create with mkdirs() a directory with a certain name.
After that you try to create a file with the same name which is impossible as there cannot be two files or directories with the same name.
So have a look and you will find that directory.
Well you had deduced most all yourself already. Now try to understand your code.
if (!file.mkdirs()) {
P.rint("Couldn't create directory");
You will see that printed every time you repeat the code. You should have seen this too. And have told us.
You should only call mkdirs if the directory does not exist yet.
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.
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.
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();
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.