I have a bean that download emails from SMTP server. After read emails it saves attachments on the server. To read attachment I use this code:
File f = new File("\\attachments\\" + attachment.getFileName());
f.mkdirs();
f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);
fos.write(bytes);
fos.close();
I got a FileNotFoundException on FileOutputStream creating and I can't understand why.
If can help, I use NetBeans with GlassFish and the tests are made in debug in local machine.
When you do
f.mkdirs();
You are creating a directory with the name of your file (that is, you create not only the directory "attachments", you also create a subdirectory with the name of your attachment filename). Then
f.createNewFile();
does not do anything since the file already exist (in the form of a directory you just created). It returns false to tell you that the file already exists.
Then this fails:
FileOutputStream fos = new FileOutputStream(f);
You are trying to open an output stream on a directory. The system doesn't allow you to write in a directory, so it fails.
The bottom line is:
mkdirs() doesn't do what you think it does.
you should check the return value of your call to createNewFile().
The simplest way to make it work is by replacing your line with:
f.getParentFile().mkdirs();
Related
I have a strange error in Java trying to output some data. I have read and write access to the file. The file exists (yourFile.exists() prints True) but still I get the Java.io.FileNotFoundException.
Sample code:
File yourFile = new File("./output/blah.txt");
FileOutputStream oFile = new FileOutputStream(yourFile);
Anyone knows anything I can try to fix this?
Beware that FileOutputStream's constructor can throw a FileNotFoundException for several different causes:
FileNotFoundException - if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason.
I am trying to write a file to internal device storage on my phone (and on user's phones in the future). I was watching a video tutorial from 2016 (https://www.youtube.com/watch?v=EhBBWVydcH8) which shows how he writes output to a file very simply. If you want to see his code, skip forward to 8:23.
Anyway, I basically tried his code, then since that didn't work, I figured would search around.
Apparently, to create a file, I need these lines of code:
String filename = "textfile.txt";
File file = new File(filename);
file.mkdirs();
file.createNewFile();
On the second line, file.createNewFile(), I get the below error:
java.io.IOException: Read-only file system
at java.io.UnixFileSystem.createFileExclusivel
at java.io.UnixFileSystem.createFileExclusivel
at java.io.File.createNewFile(File.java:948)
etc......
And then, if I run my code just by using the lines of code from the tutorial, I get a Null pointer.
Code:
try {
FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(IDNum.getBytes());
fos.close();
System.out.println("Wrote STuff Outputtt?");
} catch (Exception e) {
e.printStackTrace();
}
Error:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.FileOutputStream android.content.Context.openFileOutput(java.lang.String, int)' on a null object reference
at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:199)
at com.lecconnect.lockoutdemo.FileManager.AddUser(FileManager.java:37)
Line 37 is the first line in the try/catch.
Please let me know if you require any additional information to assist me. Your replies are greatly appreciated.
It is important to separate the directory and the file itself.
In your code, you call mkdirs on the file you want to write, which is incorrect usage because mkdirs makes your file into a directory. You should call mkdirs for the directory only, so it will be created if it does not exist, and the file will be created automatically when you create a new FileOutputStream object for this file.
Try this one:
File directory = getFilesDir(); //or getExternalFilesDir(null); for external storage
File file = new File(directory, fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(IDNum.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
I'm working with the FileOutputStream class in java, but I don't know how to delete "the contents" of a file (the main reason i need overwrite the file).
If you want to delete the contents of the file, but not the file itself, you could do:
PrintWriter pw = new PrintWriter("file.txt");
pw.close();
A few seconds of Googling got me this:
how to delete the content of text file without deleting itself
How to clear a text file without deleting it?
To delete the file completely, do:
File file = new File("file.txt");
f.delete();
Call File.delete() which deletes the file or directory denoted by this abstract pathname.
File f = new File("foo.txt");
if (f.delete()) {
System.out.println("file deleted");
}
The main reason i need overwrite the file ...
One way to do this is to delete the file using File.delete() or Files.delete(Path). The latter is preferable, since it can tell you why the deletion fails.
The other way is to simply open the file for writing. Provided that you don't open in "append" mode, opening a file to write will truncate the file to zero bytes.
Note that there is a subtle difference in the behavior of these two approaches. If you delete a file and then create a new one, any other application that has the same file open won't notice. By contrast, if you truncate the file, then other applications with the file open will observe the effects of the truncation when they read.
Actually, this is platform dependent. On some platforms, a Java application that tries to open a file for reading that another file has open for writing will get an exception.
Yes, you can do it with FileOutputStream. All the answers given say about PrintWriter but the same can be done with FileOutputStream. The int representation of space is 32. So simply pass the file to the instance of FileOutputStream as:
FileOutputStream out = new FileOutputStream(file);
out.write(32);
This will clear the contents of the file. Surely use this only of u want to do it with FileOutputStream only otherwise use PrintWriter.
I am trying to write a file in my local drive which is available in a network drive on a server. I can write this image and I can see even the size of the file available. But, when I'm opening the file it says preview not available. Content of the file is not coming.
Code which I read the network file
SmbFileInputStream sfis = null;
sfis = new SmbFileInputStream(serverFile);
fileBytes = new byte[(int) serverFile.length()];
sfis.read(fileBytes);
Code which I write the file in my local drive
FileOutputStream fos;
fos = new FileOutputStream(tempFile);
fos.write(fileBytes);
I also tried with file.copyTo method by giving my local file like a smbfile.
serverFile.copyTo(ss);
I figured it out and it works fine.
Change first two lines to
InputStream sfis = new SmbFileInputStream(serverFile);
real change is reference of the variable is now
InputStream
I am trying to get the following code to work properly. It always prints the output from the catch block, even though the output that is only printed if the file exists, is printed.
String outputFile = "/home/picImg.jpg";
File outFile = new File(outputFile);
if(outFile.exists)
newStatus(" File does indeed exist");
FileOutputStream fos;
try {
fos = new FileOutputStream(outFile);
fos.write(response);
fos.close();
return outputFile;
} catch (FileNotFoundException ex) {
newStatus("Error: Couldn't find local picture!");
return null;
}
In the code response is a byte[] containig a .jpg image from a URL. Overall I am trying to download an image from a URL and save it to the local file system and return the path. I think the issue has to do with read/write permissions within /home/. I chose to write the file there because I'm lazy and didn't want to find the username to find the path /home/USER/Documents. I think I need to do this now.
I notice in the terminal I can do cd ~ and get to /home/USER/. Is there a "path shortcut" I can use within the file name so that I can read/write in a folder that has those permissions?
No. The ~ is expanded by the shell. In Java File.exists() is a method, you can use File.separatorChar and you can get a user's home folder with System property "user.home" like
String outputFile = System.getProperty("user.home") + File.separatorChar
+ "picImg.jpg";
File outFile = new File(outputFile);
if (outFile.exists())
Edit
Also, as #StephenP notes below, you might also use File(File parent, String child) to construct the File
File outFile = new File(System.getProperty("user.home"), "picImg.jpg");
if (outFile.exists())
~ expansion is a function of your shell and means nothing special for the file system. Look for Java System Properties "user.home"
Java provides a System property to get the user home directory: System.getProperty("user.home");.
The advantage of this is, that it works for every operating system that can run the Java virtual machine.
More about System properties: Link.