Hope someone can help me.
I tried few ways of downloading files from URL but everything gives the same result - the file is there, including the file extension, but I can't open and read the file. The last way I use is
else if (!myFile.exists()) { // if file not exist
try {
String downloadPath = download_file_path+fileName;
downloadPath = URLEncoder.encode(downloadPath, "UTF-8").replace("+", "%20");
new DefaultHttpClient().execute(new HttpGet(downloadPath))
.getEntity().writeTo(
new FileOutputStream(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName))
);
} catch (IOException e) {
e.printStackTrace();
}
I tried every solutions available in SO but can't solve the problem. Please help.
Related
so I am generating files and I need to zip them to create a "Resourcepack" for Minecraft.
So on the surface, it looks like the file zips perfectly fine, however I have found some very strange behaviour. In windows, if you zip the directory itself, minecraft will not accept the zip however if you zip the contents, it will work. By the looks of it, this code achieves the first, but I can't manage to find a way to do the latter. The SHA1 of the different Zips are different so there is something going on that I cant see. When viewed they are exactly the same contents.
the code:
public static void pack(String sourceDirPath, String zipFilePath){
sourceDirPath = getDataFolder().getAbsolutePath() + "/" + sourceDirPath;
zipFilePath = getDataFolder().getAbsolutePath() + "/" + zipFilePath;
try {
Path p = Files.createFile(Paths.get(zipFilePath));
try (ZipOutputStream zs = new ZipOutputStream(Files.newOutputStream(p))) {
Path pp = Paths.get(sourceDirPath);
Files.walk(pp)
.filter(path -> !Files.isDirectory(path))
.forEach(path -> {
ZipEntry zipEntry = new ZipEntry(pp.relativize(path).toString());
try {
zs.putNextEntry(zipEntry);
Files.copy(path, zs);
zs.closeEntry();
} catch (IOException e) {
System.err.println(e);
}
});
}
}catch (IOException e){
e.printStackTrace();
}
}
EDIT:
I have looking at the properties of the contents of each zip and it looks like the correctly working one is indexing the files im still yet to find anything that allows me to do this
Can someone please tell me if what I'm doing is correct?
File directoryToStore;
directoryToStore = getBaseContext().getExternalFilesDir("MyFiles");
Bitmap b = ThumbnailUtils.createVideoThumbnail(directoryToStore + "/" + SavedVideoName, 3);
File newFile = new File(directoryToStore, SavedVideoName.replace(".mp4", ".jpg"));
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(newFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
b.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
I'm trying create a thumbnail from a video, but for some the FileOutputStream returns null.
I have checked the path of File newFile = new File(directoryToStore, SavedVideoName.replace(".mp4", ".jpg")); and it returns the correct path.
The video exists at the location I have given and I have permissions. I can't understand why it is gives me a null pointer?
According to this post, new FileOutputStream() will try to create a new file if it doesn't exist already. From the docs:
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 then a FileNotFoundException is thrown.
When you are debugging (at least in Android Studio), if you add a breakpoint and hover over newFile, it shows the file path. However, it doesn't show any details about the file, because the file doesn't (shouldn't) exist yet. You could try newFile.createNewFile() as suggested in the linked post, to confirm you are able to write the file first.
I am attempting to display PDFs to the user in their browser using a web service. Once they pass in the URL containing the variables needed. My program first downloads the PDF to local storage then proceeds to copy it to the stream and displays it. Once the viewer is able to view the PDF we wish to delete the file locally so that we do not wind up storing every file searched for. I have managed to accomplish most of this task however I am having issues deleting the file once it is displayed to the user.
Even when I attempt to manually delete the file I receive the "Currently in use in the Java SE Binary" message
Code below:
File testFile = new File("C:\\Users\\stebela\\workspace\\my-app\\invoice"+invNum+".pdf");
try
{
ServletOutputStream os = res.raw().getOutputStream();
FileInputStream inputStr = new FileInputStream(testFile);
IOUtils.copy(inputStr, os);
os.close();
inputStr.close();
//finished settings
res.status(200);
testFile.delete();
} catch (IOException e)
{
System.out.println(e.getMessage());
}
If you don't write to the file, you'r code should work.
If you call inputStr.close(); the file is no longer used by java and it can be deleted.
Pleace check, if your file is not used by any other programm. It's the best if you reboot your PC.
If it still not works, it would be interessting to know, what res is and if your file get's sendet.
I've read this part of the documentation and i think this should solve your problem.
It reads the file into a String and change the header for png images. As the http Body it uses the String of the file.
Make sure, if you change the response type, you have to change the line res.type("image/png"); to the new one.
Here you find the most common ones
File testFile = null;
try {
testFile = new File("C:\\Users\\stebela\\workspace\\my-app\\invoice"+invNum+".png");
FileInputStream fin = new FileInputStream(testFile);
int charAsInt = 0;
String httpBody = "";
while((charAsInt = fin.read()) != -1){
httpBody +=(char)charAsInt;
}
fin.close();
res.body(httpBody);
res.type("image/png");
res.status(200);
testFile.delete();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I am trying to open a PDF file when a button is clicked. However I can't seem to get this working when I run my program as a JAR.
Initially, I was using this code:
if(Desktop.isDesktopSupported())
{
try
{
File myFile = new File("src/1. Handel - And the Glory of the Lord.pdf");
Desktop.getDesktop().open(myFile);
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
}
That worked on Netbeans, however it didn't work on the JAR. After research, I found out its because I need to open it using a stream. Meaning I had to make a copy of it as a stream, and open that copy as a File. After looking around on stack overflow, I am now using this code:
try {
String inputPdf = "src/1. Handel - And the Glory of the Lord.pdf";
InputStream manualAsStream = getClass().getClassLoader().getResourceAsStream(inputPdf);
Path tempOutput = Files.createTempFile("1. Handel - And the Glory of the Lord", ".pdf");
tempOutput.toFile().deleteOnExit();
Files.copy(manualAsStream, tempOutput, StandardCopyOption.REPLACE_EXISTING);
File file = new File (tempOutput.toFile().getPath());
if (file.exists())
{
Desktop.getDesktop().open(file);
}
} catch (IOException ex) {
Logger.getLogger(HandelNotes.class.getName()).log(Level.SEVERE, null, ex);
}
This does not even work on Netbeans, whilst on another thread on Stack Exchange, the user said it worked for them.
I am getting a java.lang.NullPointerException error, on this line:
Files.copy(manualAsStream, tempOutput, StandardCopyOption.REPLACE_EXISTING);
Does anyone know what's going wrong, and could someone please tell me how to correct my code?
Thanks,
Rohan
this is a really basic one, but it got me scratch my hear for 4 hours, now i'm giving up.
to give as much as possible information , i can say it's a java webapp project with zk 5.0.8 as frontend+spring+hibernate+maven under ubuntu 11.04 with permission to the basedir set to 777.
tried the file upload everything seems to be ok and where i have confidence that my code is correct it's just not working.
here is the code
private boolean saveUploadledFile(Media uploadedMedia, String basedir) {
String code = codeGenerator.generateContentCode(15);
String FINAL_DIR_PATH = basedir + "/"+"Racing" + "/" + code;
String FINAL_FILE_PATH = FINAL_DIR_PATH + "/" + uploadedMedia.getName();
alert(FINAL_DIR_PATH);
try {
File finaldir = new File(FINAL_DIR_PATH);
//apache commons
FileUtils.forceMkdir(finaldir);
alert("Size equals" + uploadedMedia.getByteData().length);
fout = new FileOutputStream(new File(FINAL_DIR_PATH+"/"+addContentWindow1$txtName.getText()+".jar"));
//apache commons
IOUtils.copy(uploadedMedia.getStreamData(), fout);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(fout);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return false;
}
new FileOutputStream always throws exceptions. so if i can't specify where i want to save how to save the files. any ideas? i intentionally output the size of the file to make sure there is a file. Can anyone shed some light? thanks for reading this
the actual exception is
Caused by: java.io.FileNotFoundException: /joseph/mbcs/Games/Racing/20314/somthing.jar (is a directory)
I may be wrong, but isn't this part of your code faulty?
if (!finaldir.exists()) {
if (!finaldir.canWrite())
finaldir.mkdirs(); // this creates no directory no error
else
alert("Cannot write to the directory" );
}
If the directory doesn't exist, you check if you can't write there and then create it, otherwise you output an error. I think that ! there is wrong.
Might be the reason for your problem but it just as well might not be.
Leave out:
if(finalfile.canWrite()) {
as you just created the file and are writing to it.
You will get a misnamed FileNotFoundException (I think renamed in Java 7) when the OutputStream constructor failed in writing.
Another tip, general work like copying may be done using apache-commons (IOUtils, FileUtils),
i.e.:
import org.apache.commons.fileupload.util.Streams;
Streams.copy(in, out, false);