Javax : Try to find a solution to open an AVI within jar - java

I tried to open an AVI within the executable jar file, the only solution I found is to use FileOutputStream and to make a copy in a temporary file :
InputStream inputStream = getClass().getResourceAsStream(filePathInJar);
int read = 0;
byte[] bytes = new byte[1024];
this.file = new File("c:\\tmpfile.avi");
OutputStream out = new FileOutputStream(file);
while ((read = inputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
inputStream.close();
out.flush();
out.close();
And then I can make :
mediaPlayer = Manager.createRealizedPlayer(new File("c:\\tmpfile.avi").toURI().toURL());
First question : Do you have any better solution?
So with this solution I would delete the temporary file at the end of his use and I tried :
mediaPlayer.stop();
mediaPlayer.close();
mediaPlayer.deallocate();
file.delete()
But deletion doesn't work. It seems to be always in use in the player...
Second question : How can I stop the use of the temporary file or force to delete?
Thanks.

I haven't tried this, but you could try using getClass().getResource(filePathInJar) to get a URL for the resource, and then use that to construct a MediaLocator to use as the parameter to createRealizedPlayer(). Something like:
URL url = getClass().getResource(filePathInJar);
MediaLocator locator = new MediaLocator(url);
mediaPlayer = Manager.createRealizedPlayer(locator);
Edit:
So, I've verified that MediaLocator cannot deal with a jar:file:/ url.
It seems to me that you have two choices:
Find or create a custom InputStream-based DataSource. The page at http://www.extollit.com/isdsjmf.php claims to have one that works. I haven't tried it.
Keep doing what you're doing now - copy the media file from the jar to a temp file, and use a file:// url.
I think that you can solve your problem with deleting the file by using File.createTempFile() and File.deleteOnExit()

Related

Android: get real filepath from uri without copying to filestream

I am creating an app that allows the user to upload multiple files to my server and I am doing the uploading with the "Fast Android Networking" Library, so I will need to provide File Objects to upload the files and can not use the Uri's I get from the filechooser.
Currently I'm getting an InputStream from a Uri and copy it into a File.
public static void copyInputStreamToFile(InputStream inputStream,
File file) throws IOException {
try (FileOutputStream outputStream = new FileOutputStream(file, false)) {
int read;
byte[] bytes = new byte[8192];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
}
}
This though, will get any device to lag pretty fast and I'd like to avoid this. I searched everywhere but couldn't find a method for converting a Uri to a File object, that works for me. If anyone knows a way to directly upload from uri, that would also work for me.

Import csv file to mysql through jsp servlet

I am writing a web app that I would like to be able to import a csv file into a database from a jsp. Previously I have used the following code to insert the csv into the database.
LOAD DATA LOCAL INFILE "/myFileLocation.csv"
INTO TABLE myTable
COLUMNS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
ESCAPED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES;
Which works great when I have the file locally.
My question, when I upload the csv file in my jsp as a multipart. Is it possible for me to pass that PartItem file as a variable and replace the "/myFileLocation.csv" with the PartItem files temp location?
I can see the temp location when I debug and view the PartItem file which resides in repository/path under the variables table. Is this at all possible to access or do i need to parse the csv and insert it into the database that way?
I ended up finding a way to make this work. Not sure if it's the best solution but its working as I envisioned. Basically I create a string pointing to an assets folder I created in the web/resources like this.
final String mainPath = this.getServletContext().getRealPath("resources/assets");
Then I read the uploaded file, check to see if the file already exists in my assets folder, if it does I delete it.
Part filePart = request.getPart("csvFile");
String path = mainPath + "/" + filePart.getSubmittedFileName();
File fileTemp = new File(path);
if(fileTemp.exists()){
fileTemp.delete();
}
Lastly I read the uploaded file and write a new file in the location I directed it to which in this case is the assets folder I created like this.
final String fileName = filePart.getSubmittedFileName();
File convFile = new File(filePart.getSubmittedFileName());
FileOutputStream fos = new FileOutputStream(convFile);
OutputStream out = null;
InputStream filecontent= null;
try{
out = new FileOutputStream(new File(mainPath + File.separator + fileName));
filecontent = filePart.getInputStream();
int read = 0;
final byte[] bytes = new byte[1024];
while((read = filecontent.read(bytes)) != -1){
out.write(bytes, 0, read);
}
} catch (FileNotFoundException fne) {
} finally {
if (out != null) {
out.close();
}
if (filecontent != null) {
filecontent.close();
}
}
After that I just passed a string containing the path to the file with the file name to the DAO I created where I was able to utilize the sql statement I had posted above.
Like I stated before, not sure if this is the best way to do this but it seems to be working fine for me and none of my java code is contained within my jsp. If anyone has a better way of doing this or sees something wrong with what I did here let me know, I'd be very interested to hear about it.

Java : download file outside server context

I need to save a file and download file in directory outside server context.
I am using Apache Tomacat
I am able to do this in directory present in webapps directory of application
If my directory structure is as follows,
--src
--WebContent
-- uploaddir
-- myfile.txt
Then I am able to download in by simply.
download
But, problem is when file is in some other directory say d:\\uploadedfile\\myfile.txt
then I wont be able to download it, as resource is not in server context as above.
I have file path to uuid mapping,
like,
d:\\uploadedfiles\\myfile.txt <-> some_uuid
then I want file should be downloaded, on click of following,
download
So, How to make file downloadable when it is outside the server context,
I heard about getResourceAsStream() method which would do this , But would any one help me on how to do this, probably with simple code snippet?
Try the below code which you can write in filedownloadservet. Fetch the file name from the request parameter and then read and write the file.
If you need to do some security checks then do that before processing the request.
File file = new File("/home/files", "file name which user wants to download");
response.setContentType(getServletContext().getMimeType(file.getName()));
response.setContentLength(file.length());
BufferedInputStream inputStream = null;
BufferedOutputStream outputStream = null;
try {
inputStream = new BufferedInputStream(new FileInputStream(file));
outputStream = new BufferedOutputStream(response.getOutputStream());
byte[] buf = new byte[2048];
int len;
while ((len = inputStream.read(buf)) > 0) {
outputStream.write(buf, 0, len);
}
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
//log it
}
}
// do the same for input stream also
}
here i found the answer,
response.setContentType("application/msword");
response.setHeader("Content-Disposition","attachment;filename=downloadname.doc");
File file=new File("d:\\test.doc");
InputStream is=new FileInputStream(file);
int read=0;
byte[] bytes = new byte[BYTES_DOWNLOAD];
OutputStream os = response.getOutputStream();
while((read = is.read(bytes))!= -1){
os.write(bytes, 0, read);
}
os.flush();
os.close();
Base path will not work that is for HTML and it works if the base path is also exposed by your web server which does not look like case here.
To download an arbitary file you need to open the file using a FileInputStream (and surround it by a buffered input stream), read a byte, then send that byte from your servlet to the client.
Then there are security concerns, so should google that (basically not give access to any file but only file that is to be shared, audit download etc as needed.
Again in your servlet set the mime type etc and then open a input stream and write the bytes to the output stream to client

Hello world example on VFS: create a zip file from scratch

I would like to create a zip file with Commons VFS2 library. I know how to copy a file when using file prefix but for zip files write and read are not implemented.
fileSystemManager.resolveFile("path comes here")-method fails when I try path zip:/some/file.zip when file.zip is an non-existing zip-file. I can resolve an existing file but non-existing new file fails.
So how to create that new zip file then? I cannot use createFile() because it is not supported and I cannot create the FileObject before this is to be called.
The normal way is to create FileObject with that resolveFile and then call createFile for the object.
The answer to my need is the following code snippet:
// Create access to zip.
FileSystemManager fsManager = VFS.getManager();
FileObject zipFile = fsManager.resolveFile("file:/path/to/the/file.zip");
zipFile.createFile();
ZipOutputStream zos = new ZipOutputStream(zipFile.getContent().getOutputStream());
// add entry/-ies.
ZipEntry zipEntry = new ZipEntry("name_inside_zip");
FileObject entryFile = fsManager.resolveFile("file:/path/to/the/sourcefile.txt");
InputStream is = entryFile.getContent().getInputStream();
// Write to zip.
byte[] buf = new byte[1024];
zos.putNextEntry(zipEntry);
for (int readNum; (readNum = is.read(buf)) != -1;) {
zos.write(buf, 0, readNum);
}
After this you need to close the streams and it works!
In fact, it is possible to create zip files uniquely from Commons-VFS by using the following idio :
destinationFile = fileSystemManager.resolveFile(zipFileName);
// destination is created as a folder, as the inner content of the zip
// is, in fact, a "virtual" folder
destinationFile.createFolder();
// then add files to that "folder" (which is in fact a file)
// and finally close that folder to have a usable zip
destinationFile.close();
// Exception handling is left at user discretion

Create a file object from a resource path to an image in a jar file

I need to create a File object out of a file path to an image that is contained in a jar file after creating a jar file. If tried using:
URL url = getClass().getResource("/resources/images/image.jpg");
File imageFile = new File(url.toURI());
but it doesn't work. Does anyone know of another way to do it?
To create a file on Android from a resource or raw file I do this:
try{
InputStream inputStream = getResources().openRawResource(R.raw.some_file);
File tempFile = File.createTempFile("pre", "suf");
copyFile(inputStream, new FileOutputStream(tempFile));
// Now some_file is tempFile .. do what you like
} catch (IOException e) {
throw new RuntimeException("Can't create temp file ", e);
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
Don't forget to close your streams etc
This should work.
String imgName = "/resources/images/image.jpg";
InputStream in = getClass().getResourceAsStream(imgName);
ImageIcon img = new ImageIcon(ImageIO.read(in));
Usually, you can't directly get a java.io.File object, since there is no physical file for an entry within a compressed archive. Either you live with a stream (which is best most in the cases, since every good API can work with streams) or you can create a temporary file:
URL imageResource = getClass().getResource("image.gif");
File imageFile = File.createTempFile(
FilenameUtils.getBaseName(imageResource.getFile()),
FilenameUtils.getExtension(imageResource.getFile()));
IOUtils.copy(imageResource.openStream(),
FileUtils.openOutputStream(imageFile));
You cannot create a File object to a reference inside an archive. If you absolutely need a File object, you will need to extract the file to a temporary location first. On the other hand, most good API's will also take an input stream instead, which you can get for a file in an archive.

Categories