FileNotFoundException when using FileWriter - java

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.

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.

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

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.

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.

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