My program was created in Netbeans 8.0.2. The program is supposed to create a (database) folder after installation and extract the contents of a (database) jar file from its library. The folder gets created quite okay, but the contents of the jar file do not get extracted.
How can I get the extraction of the jar file to work?
NB: When I run the program in Netbeans, everything goes well.
Sample Code:
String appHomeDir = new java.io.File(".").getCanonicalPath();
String destDir = appHomeDir + "/database";
File folder = new File(destDir);
if (!folder.exists()) {
folder.mkdir();
String current = new java.io.File(".").getCanonicalPath();
String jarFile = current + "\\app\\lib\\database.jar";
java.util.jar.JarFile jar = new java.util.jar.JarFile(jarFile);
java.util.Enumeration enumEntries = jar.entries();
while (enumEntries.hasMoreElements()) {
java.util.jar.JarEntry file = (java.util.jar.JarEntry) enumEntries.nextElement();
java.io.File f = new java.io.File(destDir + java.io.File.separator + file.getName());
if (file.isDirectory()) { // if its a directory, create it
f.mkdir();
continue;
}
java.io.InputStream is = jar.getInputStream(file); // get the input stream
java.io.FileOutputStream fos = new java.io.FileOutputStream(f);
while (is.available() > 0) { // write contents of 'is' to 'fos'
fos.write(is.read());
}
fos.close();
is.close();
}
}
So the "database" directory gets created but the contents of "database.jar" do not get extracted.
Problem solved: I replaced "/app/lib/database.jar" with "/lib/database.jar"
Related
I'm able to download excel file by clicking Download button which comes under DOM ,
after that i want verify downloaded file is same one.
AUTO IT is not allowed in project.
I have tried below code for verification on local but if i will push this code to repo.
then user path will get change and code will fail.
`String filepath = "C:User\\Dhananjay\\Downloads";
String fileName = "report.xlsx"
File targetFile = new File(fileName,filePath);
if(! targetFile.exists())'
{
system.out.println("File is verified")`
}else{
system.out.println("file not downloaded")
}'
String userProfile = System.getProperty("user.home"); returns %USERPROFILE% variable.
So you can use String filepath = System.getProperty("user.home") + "\\Downloads";
Works even on Linux.
I have found way to validate on local path and it's generic one
File folder = new File(System.getProperty("user.home") +\\Downloads);
File[] listOfFiles = folder.listFiles();
boolean found = false;
File f = null;
for (File listOfFile : listOfFiles) {
if (listOfFile.isFile()) {
String fileName = listOfFile.getName();
System.out.println("File " + listOfFile.getName());
if (fileName.matches("5MB.zip")) {
f = new File(fileName);
found = true;
}
}
}
Assert.assertTrue("Downloaded document is not found",found );
f.deleteOnExit();
I wanted to zip a directory with files and subdirectories in it. I did this and worked fine but I am getting and unusual and curious file structure (At least I see it that way).
This is the created file: When I click on it, I see an "empty" directory like this: but when I unzip this I see this file structure (Not all the names are exacly as they are showed in the image below):
|mantenimiento
|Carpeta_A
|File1.txt
|File2.txt
|Carpeta_B
|Sub_carpetaB
|SubfileB.txt
|Subfile1B.txt
|Subfile2B.txt
|File12.txt
My problem somehow is that the folder "mantenimiento" is where I am zippping from (the directory which I want to zip) and I dont want it to be there, so when I unzip the just created .zip file I want it with this file structure (which are the files and directories inside "mantenimiento" directory): and the other thing is when I click on the .zip file I want to see the files and directories just like the image showed above.
I dont know what's wrong with my code, I have searched but haven't found a reference to what my problem might be.
Here's my code:
private void zipFiles( List<File> files, String directory) throws IOException
{
ZipOutputStream zos = null;
ZipEntry zipEntry = null;
FileInputStream fin = null;
FileOutputStream fos = null;
BufferedInputStream in = null;
String zipFileName = getZipFileName();
try
{
fos = new FileOutputStream( File.separatorChar + zipFileName + EXTENSION );
zos = new ZipOutputStream(fos);
byte[] buf = new byte[1024];
int len;
for(File file : files)
{
zipEntry = new ZipEntry(file.toString());
fin = new FileInputStream(file);
in = new BufferedInputStream(fin);
zos.putNextEntry(zipEntry);
while ((len = in.read(buf)) >= 0)
{
zos.write(buf, 0, len);
}
}
}
catch(Exception e)
{
System.err.println("No fue posible zipear los archivos");
e.printStackTrace();
}
finally
{
in.close();
zos.closeEntry();
zos.close();
}
}
Hope you guys can give me a hint about what I am doing wrong or what I am missing.
Thanks a lot.
Btw, the directory i am giving to the method is never used. The other parameter i am giving is a list of files which contains all the files and directories from the C:\mantenimiento directory.
I once had a problem with windows and zip files, where the created zip did not contain the entries for the folders (i.e. /, /Carpeta_A etc) only the file entries. Try adding ZipEntries for the folders without streaming content.
But as alternative to the somewhat bulky Zip API of Java you could use Filesystem (since Java7) instead. The following example is for Java8 (lambda):
//Path pathToZip = Paths.get("path/to/your/folder");
//Path zipFile = Paths.get("file.zip");
public Path zipPath(Path pathToZip, Path zipFile) {
Map<String, String> env = new HashMap<String, String>() {{
put("create", "true");
}};
try (FileSystem zipFs = FileSystems.newFileSystem(URI.create("jar:" + zipFile.toUri()), env)) {
Path root = zipFs.getPath("/");
Files.walk(pathToZip).forEach(path -> zip(root, path));
}
}
private static void zip(final Path zipRoot, final Path currentPath) {
Path entryPath = zipRoot.resolve(currentPath.toString());
try {
Files.createDirectories(entryPath.getParent());
Files.copy(currentPath, entryPath);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
there is folder temp to which the files uploaded by users are stored. the file name is same for each user but the content is different. Each user uploads a file called abc.xlsx. now when "A" user uploads abc.xlsx file after processing that file should be deleted. But currently i am deleting all the files in the folder. which is a problem since one more user might be uploading the file ehich will be cleared too. So i was thinking of renaming the file by appending the username to the file and then delete that particular file.
This is the file upload:
ProcessForm uploadForm = (ProcessForm)form;
String folderpath = "servers/temp";
String filePath = folderpath + "/" + uploadForm.getUploadedFile().getFileName();
This will delete all the files in the folder:
String tempPath = folderpath;
File file = new File(tempPath);
File[] files = file.listFiles();
for (File f:files)
{
if (f.isFile() && f.exists())
{
f.delete();
}
}
I think i got it. This is working as expected:
String folderpath = "servers/temp";
String filePath = folderpath + "/" + "abc_"+user.getUsername()+".xlsx";
outputStream = new FileOutputStream(new File(filePath));
outputStream.write(uploadForm.getUploadedFile().getFileData());
Code to delete file:
File file = new File(filePath);
boolean fileDelete = file.delete();
if (fileDelete)
{
mLogger.debug("successfully deleted");
} else {
mLogger.error("cant delete a file");
}
i want to include a file into my project in Netbeans, i'm developping an application for PC with the language Java. I searched almost on the Net, but i have found nothing. When i compile the application if i go into path where there is /dist the file exe aren't here.
Thank you so much.
String exec [] = {getClass().getClassLoader().getResource("inc_volume.exe").getPath() };
System.out.println(exec[0]);
Runtime.getRuntime().exec(exec);
Update on 20/08/2014 15.29
I have found this source to extract from jar, but i don't know how to use:
java.util.jar.JarFile jar = new java.util.jar.JarFile(jarFile);
java.util.Enumeration enumEntries = jar.entries();
while (enumEntries.hasMoreElements()) {
java.util.jar.JarEntry file = (java.util.jar.JarEntry) enumEntries.nextElement();
java.io.File f = new java.io.File(destDir + java.io.File.separator + file.getName());
if (file.isDirectory()) { // if its a directory, create it
f.mkdir();
continue;
}
java.io.InputStream is = jar.getInputStream(file); // get the input stream
java.io.FileOutputStream fos = new java.io.FileOutputStream(f);
while (is.available() > 0) { // write contents of 'is' to 'fos'
fos.write(is.read());
}
fos.close();
is.close();
}
Here Image:
To include an exe file to your project, copy this exe file via filesystem to the src folder of your Netbeans project.
when you have built your project, then this exe file will be packaged into the project jar file.
At runtime to run this exe, you will need to extract this exe file from your jar file.
And as this exe file is extracted you can execute it.
To launch an external application from your java code I recommend to use Apache Commons Exec: http://commons.apache.org/proper/commons-exec/
UPDATE
Below there's sample class to demonstrate how to extract all exe files from the current running jar file. I used these SO posts to make this class: the first and the second ones.
import java.io.File;
import java.io.IOException;
/**
*
*/
public class TestClass {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
extractExeFiles("C://Temp");
}
/**
* Gets running jar file path.
* #return running jar file path.
*/
private static File getCurrentJarFilePath() {
return new File(TestClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
}
/**
* Extracts all exe files to the destination directory.
* #param destDir destination directory.
* #throws IOException if there's an i/o problem.
*/
private static void extractExeFiles(String destDir) throws IOException {
java.util.jar.JarFile jar = new java.util.jar.JarFile(getCurrentJarFilePath());
java.util.Enumeration enumEntries = jar.entries();
String entryName;
while (enumEntries.hasMoreElements()) {
java.util.jar.JarEntry file = (java.util.jar.JarEntry) enumEntries.nextElement();
entryName = file.getName();
if ( (entryName != null) && (entryName.endsWith(".exe"))) {
java.io.File f = new java.io.File(destDir + java.io.File.separator + entryName);
if (file.isDirectory()) { // if its a directory, create it
f.mkdir();
continue;
}
java.io.InputStream is = jar.getInputStream(file); // get the input stream
java.io.FileOutputStream fos = new java.io.FileOutputStream(f);
while (is.available() > 0) { // write contents of 'is' to 'fos'
fos.write(is.read());
}
fos.close();
is.close();
}
}
}
}
I have a project(project source) with .txt file which I want to access from other project (project caller). caller has dependecy over source. So caller should see source as .jar. Well, the question, I have to access to this .jar to obtenin the .txt file but I cannot. I have tried thinks like:
getClass().getResourceAsStream("classpath:/cc.txt"); with InsputStream
and getClass().getResource("cc.txt"); with URL object
but I always got a null. All forums I ve read speaks about this way to access.
How do I suposse to access to a .jar file to get the .txt file?
thanks all!!
Extract the Contents of ZIP/JAR Files Programmatically. Suppose jarFile is the jar/zip file to be extracted. destDir is the path where it will be extracted:
java.util.jar.JarFile jar = new java.util.jar.JarFile(jarFile);
java.util.Enumeration enum = jar.entries();
while (enum.hasMoreElements())
{
java.util.jar.JarEntry file = (java.util.jar.JarEntry) enum.nextElement();
java.io.File f = new java.io.File(destDir + java.io.File.separator + file.getName());
if (file.isDirectory()) // if its a directory, create it
{
f.mkdir();
continue;
}
java.io.InputStream is = jar.getInputStream(file); // get the input stream
java.io.FileOutputStream fos = new java.io.FileOutputStream(f);
while (is.available() > 0) // write contents of 'is' to 'fos'
{
fos.write(is.read());
}
fos.close();
is.close();
}
the same question can be found here...