Is there an open dialog to select a file inside a Jar? - java

I am looking for a dialog that will be able to browse to content of jar file (or even better allow me to browse the file system and then get into the jar file).
Ideally the dialog should return a classloader for the jar and the url of the selected resource.
Can anybody point me to some sample code to do that ?
Thanks

You need to implements you own FileSystemView that will be able to go into ZIP/JAR files and then pass this implementation to JFileChooser constructor. If you need more details, feel free to ask more questions.

JAR is basically a zip file. You can open it with standard ZIP library for Java.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class JarAccess
{
public static void main(String[] args) throws IOException
{
if (args.length != 1)
{
System.err.println("usage: java JarAccess name_or_your_jar.jar");
return;
}
try (ZipInputStream zis =
new ZipInputStream(new FileInputStream(args[0])))
{
byte[] buffer = new byte[4096];
ZipEntry ze;
while ((ze = zis.getNextEntry()) != null)
{
System.out.println("Extracting: "+ze);
try (FileOutputStream fos = new FileOutputStream(ze.getName()))
{
int numBytes;
while ((numBytes = zis.read(buffer, 0, buffer.length)) != -1)
fos.write(buffer, 0, numBytes);
}
zis.closeEntry();
}
}
}
}
source
(code is untested, but logically it should work)

Related

Unable to delete specific files after unzipping the files

Am new to Java, I searched in google for unzipping the files. Tested the code in my local and am able to unzip the files.
But unable to delete the files I tried some logic but no luck.
Can anyone help me how read a particular file and delete that file using its path and also need to delete a specific folder using its path and delete recursively. all the other files need to be there
Below is the code:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class UnzipFiles {
public static void main(String[] args) {
String zipFilePath = "/Users/Safeer_Pasha/Music/archive.zip";
String destDir = "/Workspace/";
unzip(zipFilePath, destDir);
}
private static void unzip(String zipFilePath, String destDir) {
File dir = new File(destDir);
// create output directory if it doesn't exist
if(!dir.exists()) dir.mkdirs();
FileInputStream fis;
//buffer for read and write data to file
byte[] buffer = new byte[1024];
try {
fis = new FileInputStream(zipFilePath);
ZipInputStream zis = new ZipInputStream(fis);
ZipEntry ze = zis.getNextEntry();
while(ze != null){
String fileName = ze.getName();
File newFile = new File(destDir + File.separator + fileName);
System.out.println("Unzipping to "+newFile.getAbsolutePath());
//create directories for sub directories in zip
new File(newFile.getParent()).mkdirs();
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
//close this ZipEntry
zis.closeEntry();
ze = zis.getNextEntry();
}
//close last ZipEntry
zis.closeEntry();
zis.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Copying Jar file without corruption

I need to copy a .jar file (which is a resource in my project) from a separate runnable jar to the startup folder in windows. Here's the code I have so far.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class Installer {
public static void main(String[] args) throws IOException
{
InputStream source = Installer.class.getResourceAsStream("prank.jar");
byte[] buffer = new byte[source.available()];
source.read(buffer);
File targetFile = new File(System.getProperty("user.home") + File.separator + "AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\prank.jar");
OutputStream outStream = new FileOutputStream(targetFile);
outStream.write(buffer);
outStream.close();
}
}
My problem is that after the jar file is copied, it is corrupt (although the size of the original and the copy are the same.) Any thoughts on how to do this and have a runnable jar at the end of the process?
Refer to InputStream#available does not work.
The following line
byte[] buffer = new byte[source.available()];
is not correct, as available only return estimate of the size, the jar will be corrupted when estimate is different with actual. (Example from Java – Write an InputStream to a File) seems incorrect as I can't find any reference that guarantee correctness of available for FileInputStream.
Solution from How to convert InputStream to File in Java is more robust,
private static void copyInputStreamToFile(InputStream inputStream, File file)
throws IOException {
try (FileOutputStream outputStream = new FileOutputStream(file)) {
int read;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
// commons-io
//IOUtils.copy(inputStream, outputStream);
}
}
You can consider to use
IOUtils#copy(InputStream, OutputStream)
Files#copy(InputStream, Path, CopyOption...) suggested by Holger for jdk 1.7 or above
Try this -
Path source = Paths.get("location1/abc.jar");
Path destination = Paths.get("location2/abc.jar");
try {
Files.copy(source, destination);
} catch(FileAlreadyExistsException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

File Not Found Exception, Access is Denied, Java

I made a Program which moves all files of a folder to another folder but when I'm executing the Program it shows me java.io.FileNotFound Exception and Access is denied
I tried to fix this error but it is still giving me the same error.
What am I doing wrong?
I have also attached the screenshot of Error I am getting.
when I checked the properties of the folder it was read-only, I changed but still, the Issue Persists
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MoveFile
{
public static void main(String\[\] args)
{
InputStream inStream = null;
OutputStream outStream = null;
try{
File afile =new File("C:\\Users\\admin\\Desktop\\A");
File bfile =new File("C:\\Users\\admin\\Desktop\\B");
inStream = new FileInputStream(afile);
outStream = new FileOutputStream(bfile);
byte\[\] buffer = new byte\[1024\];
int length;
while ((length = inStream.read(buffer)) > 0){
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
afile.delete();
System.out.println("File Moved!");
}catch(IOException e){
e.printStackTrace();
}
}
}
I expect the Files of folder A to move in Folder B.
according to your question description , you try to move all file of a folder to another folder...
to do this you can use this code ....
public static void main(String[] args) throws IOException {
String from = "C:/Users/Infra/Desktop/PBL/A";
String to = "C:/Users/Infra/Desktop/PBL/B";
File folder = new File(from);
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
Path temp = Files.move(Paths.get(from +"/"+ file.getName()),
Paths.get(to +"/"+ file.getName()));
}
}

how to create zip inside the other zip.i got the fileNotFoundException

How to create zip inside zip file
enter image description here
got bellow Error:
D:\sagar\my work\Package Maker\DirectoryStruct>java zipStructure
java.io.FileNotFoundException: Additional_Sub_Folder\Additional_file.zip (The sy
stem cannot find the path specified)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:221)
at java.io.FileOutputStream.<init>(FileOutputStream.java:110)
at zipStructure.main(zipStructure.java:22)
D:\sagar\my work\Package Maker\DirectoryStruct> that is Additional_sub_folder and Digital_sub_folder. inside Additional_sub_folder 1 zip file created(Additional_file.zip),inside that zip 2 folder are created like xml folder and pdf folder
and inside Digital_sub_folder create Artical_sub_folder,and inside Artical_sub_folder 3 new folder are created that is xml folder,pdf folder and Graphics folder. i try it be below java code but not works properly,please help to create the this structure.
import java.io.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class zipStructure {
public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream("main.zip");
ZipOutputStream zos = new ZipOutputStream(fos);
zos.putNextEntry(new ZipEntry("Additional_Sub_Folder/"));
zos.putNextEntry(new ZipEntry("Digital_Sub_Folder/"));
FileOutputStream fos1 = new FileOutputStream("Additional_Sub_Folder/Additional_file.zip");
ZipOutputStream zos1 = new ZipOutputStream(fos1);
/*zos1.putNextEntry(new ZipEntry("Additional_file.zip/xml/"));
zos1.putNextEntry(new ZipEntry("Additional_file.zip/pdf/"));*/
zos1.putNextEntry(new ZipEntry("Additional_file1.zip/xml/"));
zos1.putNextEntry(new ZipEntry("Additional_file1.zip/pdf/"));
zos1.close();
fos1.close();
zos.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void addToZipFile(String fileName, ZipOutputStream zos) throws FileNotFoundException, IOException {
System.out.println("Writing '" + fileName + "' to zip file");
File file = new File(fileName);
FileInputStream fis = new FileInputStream(file);
ZipEntry zipEntry = new ZipEntry(fileName);
zos.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zos.write(bytes, 0, length);
}
zos.closeEntry();
fis.close();
}
}
[1]: http://i.stack.imgur.com/TNA8b.jpg
I did not have the problem with the zip-I/O, I had the FileNotFoundException with every type of I/O that uses the fileSystem.
What helped for me was, if you're working with eclipse, that there is function like "refresh project" or something like this. Everytime I had problems with I/O, that worked.

Get file from the specified path

I need to read a file from a specified path. E.g: I have a file called abc.txt and it resides inside /dev/user/assets/data/abc.png.
If one has to read from a Zip file we do something like
Zipfile zipFile = new ZipFile("test.zip");
ZipEntry entry = zipFile.getEntry(imagePath); // where image path is /dev/user/assets/data/abc.png.
Is there a code something similar to the above for reading from a folder?
Like
File folder = new Folder("Users");
and give the path "/dev/user/assets/data/abc.png" to the above and read the image.
Yes, File has two-args constructor File(File parent, String child) that does exactly what you describe (you may just have to throw the leading '/' of the child). Take a look at the JavaDoc
I'm not sure if I understand exactly what you want to do. But if what you want to do is simply to read the contents of a file with a given path, then you should'nt use the File API.
Instead you should use a new FileReader(textFilePath); or a new FileInputStream(imageFilePath);
Look at the following example, taken from the java tutorials.
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.IOException;
public class CopyLines {
public static void main(String[] args) throws IOException {
BufferedReader inputStream = null;
PrintWriter outputStream = null;
try {
inputStream = new BufferedReader(new FileReader("xanadu.txt"));
outputStream = new PrintWriter(new FileWriter("characteroutput.txt"));
String l;
while ((l = inputStream.readLine()) != null) {
outputStream.println(l);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
}

Categories

Resources