How to convert an InputStream object to a File object? - java

I'm trying to get a "File" instance in a servlet called from a html form, in which I can select a PDF file on my computer.
I'm successful in getting the file as an "InputStream" but then I just cannot further convert it to a "File" object.
After a lot of different attempts, I still can't figure out what I should be doing to make it work. Any idea ?
Error :
java.io.FileNotFoundException: test.pdf (Read-only file system)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(FileOutputStream.java:270)
at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
at org.apache.commons.io.FileUtils.openOutputStream(FileUtils.java:360)
at org.apache.commons.io.FileUtils.openOutputStream(FileUtils.java:319)
at org.apache.commons.io.FileUtils.copyToFile(FileUtils.java:1552)
at org.apache.commons.io.FileUtils.copyInputStreamToFile(FileUtils.java:1528)
Code :
Part filePart = request.getPart("file");
InputStream fileContent = filePart.getInputStream();
if (fileContent != null)
{
File file = new File(filename.trim() + ".pdf");
FileUtils.copyInputStreamToFile(fileContent, file);
//use the "file" instance
//...
}

As the exception is telling you, the problem is not with "creating the file". The problem is the disk/partition is write-protected
You should create the file on a file system that is writable. Try to specify an absolute path, such as
File file = new File("/tmp/" + filename.trim() + ".pdf");
//or
file = new File("/home/userhome/" + filename.trim() + ".pdf");
The file should just be created on a writable file system.

Related

How to write an image to file – Java ImageIO

I would like to write an image to a file using Java ImageIO. This is my piece of code:
Document doc = convertDocument (fileName, "grey");
ImageIO.write(Converter.convertSVGToPNG(doc), "png",
new File(FOLDER_PNG_OUT_GREY + fileName.replaceAll(".svg", ".png")));
But I get this error when running my code:
java.io.FileNotFoundException: C:\Work\eclipse-tdk\svgManager\svgManager\src\main\resources\icons\svg\grey_png\$pac.png (The system cannot find the path specified)
I also tried:
String pngFileName = FOLDER_PNG_OUT_GREY + fileName.replaceAll(".svg", ".png");
File outputfile = new File(pngFileName);
bImage = ImageIO.read(outputfile);
but then I got the error:
Can't read input file!
I suggest to get your image resource with the getResource(String file) method like this:
File initialImage = new File(YourClass.class.getResource("pac.png").getFile());

How to get the original file name when downloading file with java

How to get original file name when i download file from URL with java like this
File file = new File( "test" ) ;
FileUtils.copyURLToFile(URL, file)
Because when i create file i must put a name but at this stage i don't know yet the original name of downloading file.
For me the suggested file name is stored in the header file Content-Disposition:
Content-Disposition: attachment; filename="suggestion.zip"
I am downloading a file from nexus, so for different servers/applications it might be stored in a different header field but it is easy to find out with some tools like firebug for firefox.
The following lines work fine for me
URL url = new URL(urlString);
// open the connection
URLConnection con = url.openConnection();
// get and verify the header field
String fieldValue = con.getHeaderField("Content-Disposition");
if (fieldValue == null || ! fieldValue.contains("filename=\"")) {
// no file name there -> throw exception ...
}
// parse the file name from the header field
String filename = fieldValue.substring(fieldValue.indexOf("filename=\"") + 10, fieldValue.length() - 1);
// create file in systems temporary directory
File download = new File(System.getProperty("java.io.tmpdir"), filename);
// open the stream and download
ReadableByteChannel rbc = Channels.newChannel(con.getInputStream());
FileOutputStream fos = new FileOutputStream(download);
try {
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
} finally {
fos.close();
}

Save to desktop without the exact path

I want to save a file in my desktop. So I have
FileOutputStream out = new FileOutputStream(new File("C:\\path_to_Dekstop\\print.xls"));
and it works. But I want to save the file without put the exact path to the desktop. I searched it and I found similar questions and I came up with this solution:
File desktopDir = new File(System.getProperty("user.home"), "Desktop");
System.out.println(desktopDir.getPath() + " " + desktopDir.exists());
String pathToDesktop = desktopDir.getPath();
FileOutputStream out = new FileOutputStream(new File(pathToDesktop));
but I got an error
java.io.FileNotFoundException: C:\Users\nat\Desktop (Access is denied)
pathToDesktop represents the directory of the Desktop, you should supply a file name to write to
FileOutputStream out = new FileOutputStream(new File(desktopDir, "File to be written to"));
Which will place the "File to be written to" on the desktop
You can't write directly to Desktop as its a folder but not a file. You need to write to a file. DO something like thi s:-
File desktopDir = new File(System.getProperty("user.home"), "Desktop");
System.out.println(desktopDir.getPath() + " " + desktopDir.exists());
String pathToDesktop = desktopDir.getPath();
FileOutputStream out = new FileOutputStream(new File(pathToDesktop+System.getProperty("file.separator")+"print.xls"));
This will write to print.xls in Desktop.

How to upload file to Dropbox?

I want to upload a file to drop-box using a web-application. But the problem is that Java is asking the complete file path. What do I have to do? This is my code:
File inputFile = new File("D://New Text Document.txt");
System.out.println("inputFile.getAbsoluteFile(): " + inputFile);
FileInputStream inputStream = new FileInputStream("D://New Text Document.txt");
try {
DbxEntry.File uploadedFile = client.uploadFile("/magnum-opus.txt",
DbxWriteMode.add(), inputFile.length(), inputStream);
System.out.println("Uploaded: " + uploadedFile.toString());
} finally {
inputStream.close();
}
In the first line it is asking for the file path; how is this possible?
you can use relative path
File inputFile = new File("working-draft.txt");
FileInputStream inputStream = new FileInputStream(inputFile);
try {
DbxEntry.File uploadedFile = client.uploadFile("/magnum-opus.txt",
DbxWriteMode.add(), inputFile.length(), inputStream);
System.out.println("Uploaded: " + uploadedFile.toString());
} finally {
inputStream.close();
}
more details here
The Dropbox Java Core SDK tutorial has the following code as a sample for uploading a file:
File inputFile = new File("working-draft.txt");
FileInputStream inputStream = new FileInputStream(inputFile);
try {
DbxEntry.File uploadedFile = client.uploadFile("/magnum-opus.txt",
DbxWriteMode.add(), inputFile.length(), inputStream);
System.out.println("Uploaded: " + uploadedFile.toString());
} finally {
inputStream.close();
}
In the sample above, in the first line, "working-draft.txt" is the local path to a local file. This needs to point to an existing local file. Your code has "D://New Text Document.txt" so you should first make sure there is actually a file there.
In the fourth line, "/magnum-opus.txt", the first parameter passed to uploadFile, is the desired remote path, that is, where in the Dropbox folder you want to upload the file to. The API requires remote paths be referenced relatively like this. The uploadFile method is documented here.

java.io.FileNotFoundException:

I am Trying to Copy Single file from Source to Destination using Java but getting following Error message.
java.io.FileNotFoundException: Following is the method
public void copy_single(String source,String dest,String filename)
{
try
{ System.out.println(source + "" + filename);
System.out.println(dest + "" + filename);
File inputFile = new File(source+""+filename);
File outputFile = new File(dest+""+filename);
Process proc0 = Runtime.getRuntime().exec("chmod -R 777 "+inputFile+"");
proc0.waitFor();
Process proc1 = Runtime.getRuntime().exec("chmod -R 777 "+outputFile+"");
proc1.waitFor();
FileReader in = new FileReader(inputFile);
FileWriter out = new FileWriter(outputFile);
int c;
while ((c = in.read()) != -1)
out.write(c);
in.close();
out.close();
} catch(Exception e) {
e.printStackTrace();
System.out.println("Error: Operation failed!");
}
}
Output:-
/home/root/Tool/AAputDelta.sh
/home/root/Desktop/Sqa/BaseLine/Engine/AAputDelta.sh
java.io.FileNotFoundException: /home/root/Desktop/Sqa/BaseLine/Engine/AAputDelta.sh (No such file or directory)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:194)
at java.io.FileOutputStream.<init>(FileOutputStream.java:145)
How to copy simple file using java.
Suspect that some or all of dest output path may not exist. If this is the case you could use File.mkdirs to build the path.
Also, rather than building the file from strings, would suggest allowing File handle all this, e.g.:
File inputFile = new File(source, filename);
File outputFile = new File(dest, filename);
Use apache commons FileUtils. Any of these should be sufficient
FileUtils.copyFile(File srcFile, File destFile)
FileUtils.copyFile(File srcFile, File destFile, boolean preserveFileDate)
FileUtils.copyFileToDirectory(File srcFile, File destDir)
FileUtils.copyFileToDirectory(File srcFile, File destDir, boolean preserveFileDate)
You can use FileUtils from commons-io :
http://commons.apache.org/io/apidocs/org/apache/commons/io/FileUtils.html
or the Files from Java 7 :
http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html
java.io.FileNotFoundException Means that some file was not found so check the values :
source
dest
filename
source+""+filename
dest+""+filename
If the file doesn't exist, the filesystem will try to create the file. If creation fails, Java will throw FileNotFountException.
Maybe you need add
File outputFile = new File(dest+""+filename);
if(!outputFile.exist())outputFile.createNewFile();

Categories