How to get the unzipped file directory by using TrueZip - java

public class unzipAll {
public static void main(final java.lang.String[] args) throws Exception{
TFile src = new TFile("C:/1/BULK.tar.gz");
File dest = new File("C:/Test/");
dest.mkdirs();
try {
src.cp_rp(dest);
TVFS.umount();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I can use this code to unzip BULK.tar.gz. But I want to know the directory of the unzipped files.
Right now, all the files unzipped to C:/Test/. But it has a sub folder "AAAAA".
I want to get this sub folder name "AAAAA" How can I get it?

Try dest.listFiles(). It should give you an array of all files and directories in dest. There are also versions of listFiles that can filter out different kinds of files and/or directories which can be handy at times.
See java api for details: http://docs.oracle.com/javase/7/docs/api/java/io/File.html

Related

Text and image files not included when exporting jar

I've created a project which utilizes image files as well as a text file when executed. Both the text and image files are in my project folder before I exported the project into a runnable jar, but when I ran the jar from the command line, I got a filenotfound exception caused by the program typing to read from the text file. I unzipped the jar to double check and the image and text files weren't there.
package application;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import javafx.collections.FXCollections;
public class Data {
private static Data instance=new Data();
private Map<String,String> saveEntries = new HashMap<>();
private static String fileName = "ResponseData";
public static Data getInstance() {
return instance;
}
public void exitSave() throws IOException {
Path path = Paths.get("ResponseData");
Iterator<Map.Entry<String, String>> iter = saveEntries.entrySet().iterator();
BufferedWriter bw = Files.newBufferedWriter(path);
try {
while(iter.hasNext()) {
Map.Entry<String, String> entry = iter.next();
bw.write(String.format("%s\t%s", entry.getKey(),entry.getValue()));
bw.newLine();
}
} catch (IOException e) {
new FileNotFoundException("Error when saving data");
}finally {
if(bw!=null)
bw.close();
}
}
public void updatedSaveEntry(String input, String response) {
saveEntries.put(input, response);
}
public Map<String,String> getSaveEntries(){
return this.saveEntries;
}
public void setEntry(Map<String,String> map) {
Iterator<Map.Entry<String, String>> iter = map.entrySet().iterator();
while(iter.hasNext()) {
Map.Entry<String, String> entry = iter.next();
saveEntries.put(entry.getKey(), entry.getValue());
}
}
public void loadEntries() throws IOException{
saveEntries = FXCollections.observableHashMap();
Path path = Paths.get(fileName);
BufferedReader br = Files.newBufferedReader(path);
String line;
try {
while((line=br.readLine())!=null&&!line.trim().isEmpty()) {
String[] parts = line.split("\t");
saveEntries.put(parts[0], parts[1]);
}
}finally {
if(br!=null) {
br.close();
}
}
}
}
Eclipse Runnable Jar Export
Project Folder
If you are both reading and writing to a file, then locating this file in the application jar is not appropriate as mentioned in the other answer: you should persist your data at an external location.
However, it is usual to keep the read-only resources files (such as images) in the jar. If you want to keep this approach for the images and possibly other resources, you are facing two problems:
Getting Eclipse to include the file in the jar using the Export Runnable Jar feature.
Finding the file in the jar
Including the file
The simplest is probably just to place the file in a source folder. In your project, do New -> Source Folder, give it a name (e.g., "resources"), and move your file there. Normally, if you re-run the export, the file should be in the jar.
Finding the file
Files in jar are accessed differently. See the accepted answer to Reading a resource file from within jar. Note that you don't need to include the name of your resource folder in the path, as this file will be placed at the root of your jar (you can verify this by unpacking it).
Your program is trying to read the file from your local file system and not from the jar file. So it should indeed not be included in the jar file. The program is expecting the file in the current working directory where you execute your program and that can be different if you run your project within Eclipse or if you execute the exported jar file.

TrueZip unable to extract file from archive

I am creating a java app that will extract the embedded thumbnail inside of a Powerpoint (PPTX) document. Since pptx files are zip archives, I am trying to use TrueZip to get the thumbnail found inside of the archive. Unfortunately whenever I try running my application it throws an IOException stating that the file is missing C:\Users\test-user\Desktop\DocumentsTest\Hello.pptx\docProps\thumbnail.jpeg (missing file)
Below is the code I use to get the thumbnail:
public Boolean GetThumbPPTX(String inFile, String outFile)
{
try
{
TFile srcFile = new TFile(inFile, "docProps\\thumbnail.jpeg");
TFile dstFile = new TFile(outFile);
if(dstFile.exists())
dstFile.delete();
srcFile.toNonArchiveFile().cp_rp(dstFile);
return dstFile.exists();
} catch (IOException ex) {
Logger.getLogger(DocumentThumbGenerator.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
Where inFile is the absolute path of the pptx file and outFile is the path that the thumbnail will be copied to. I can verify that the archive does have a thumbnail inside of it at the same exact path.
Can someone help please?
I just found the answer. It seems I did not have the Zip driver configured correctly. I added this to my class constructor and it all works now:
TConfig.get().setArchiveDetector(new TArchiveDetector(
TArchiveDetector.NULL,
new Object[][] {
{ "zip|pptx", new ZipDriver(IOPoolLocator.SINGLETON)},
}));

Exporting image in runnable jar doesn't work

I'm having a weird problem in java. I want to create a runnable jar:
This is my only class:
public class Launcher {
public Launcher() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
String path = Launcher.class.getResource("/1.png").getFile();
File f = new File(path);
JOptionPane.showMessageDialog(null,Boolean.toString(f.exists()));
}
}
As you can see it just outputs if it can find the file or not. It works fine under eclipse (returns true). i've created a source folder resources with the image 1.png. (resource folder is added to source in build path)
As soon as I export the project to a runnable jar and launch it, it returns false.
I don't know why. Somebody has an idea?
Thanks in advance
edit: I followed example 2 to create the resources folder: Eclipse exported Runnable JAR not showing images
If you would like to load resources from your .jar file use getClass().getResource(). That returns a URL with correct path.
Image icon = ImageIO.read(getClass().getResource("imageĀ“s path"));
To access images in a jar, use Class.getResource().
I typically do something like this:
InputStream stream = MyClass.class.getResourceAsStream("Icon.png");
if(stream == null) {
throw new RuntimeException("Icon.png not found.");
}
try {
return ImageIO.read(stream);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
stream.close();
} catch(IOException e) { }
}
Still you're understand, Kindly go through this link.
Eclipse exported Runnable JAR not showing images
Because the image is not separate file but packed inside the .jar.
Use the code to create the image from stream
InputStream is=Launcher.class.getResourceAsStream("/1.png");
Image img=ImageIO.read(is);
try to use this to get image
InputStream input = getClass().getResourceAsStream("/your image path in jar");
Two Simple steps:
1 - Add the folder ( where the image is ) to Build Path;
2 - Use this:
InputStream url = this.getClass().getResourceAsStream("/load04.gif");
myImageView.setImage(new Image(url));

FileNotFoundException in Eclipse

In Eclipse, my directory structure is this:
-src
-com.xxx.yyy
- MyClass.java
-assets
- car.txt
MyClass.java looks like this :
public class MyClass {
private static String FILE_PATH = "../assets/car.txt";
public static void main(String[] args) {
try {
//FileNotFoundException
FileInputStream fis = new FileInputStream(new File(FILE_PATH));
}
...
}
}
I this by default, the classpath is src/, so I point to my car.txt file by ../assets/car.txt. But I get :
java.io.FileNotFoundException: ../assets/car.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
Why ?
Relative file paths a relative to the execution, assuming that the program is executed in the same location as the src and assets directory, then the path should be assets/car.txt
You can check the current execution location using System.out.println(new File(".").getCanonicalPath());
Whe you run the program it is compiled to the parent folder of the src folder as far as I know. You should better add the assets folder to your build path and access the file using getClass().getResource[AsStream]().
To add the folder do the following:
Right click on your project
Click Build Path
Choose Configure Build Path
Select Source
Click Add Folder...
Select your assets folder
Inside your code you can either call it with MyClass.class.getResource[AsStream]() or getClass().getResource[AsStream]().
getResource() returns an URL and getResourceAsStream() an InputStream. Both methods expect a path as parameter. Check the docs for more information.
Your path is incorrect
Since you are inside com.xxx.yyy, you are inside three folders. You need to get out of all of them.
So you can use, the relative path as
FILE_PATH = "../../../assets/car.txt";
As src is a source folder, all the contents come directly in the classpasth, you can also use
FILE_PATH = "assets/car.txt";
You are in second level in directory structure.
Try
FILE_PATH = "../../assets/car.txt";
Hope, this will help you...
package com.xxx.yyy;
import java.io.File;
import java.io.FileInputStream;
public class MyClass {
private static String FILE_PATH = "src/assets/car.txt";
public static void main(String[] args) {
try {
//FileNotFoundException
FileInputStream fis = new FileInputStream(new File(FILE_PATH));
}
catch (Exception e){
e.printStackTrace();
}
}
}
Ankit Lamba 's suggestion works: that's using String FILE_PATH = "assets/car.txt";

How do I automatically convert all javadoc package.html files into package-info.java files?

We use a lot of legacy package.html files in our project and we want to convert them to package-info.java files. Doing that manually isn't an option (way too many files). Is there a good way to automate that?
We want to convert them for a couple of reasons:
From the javadoc specs: This file is new in JDK 5.0, and is preferred over package.html.
To not mix both types of files in the same codebase
To avoid that Intellij/Eclipse builds put those *.html files in our classes dirs (and possibly in a release binary jars) so they behave like our other normal html resources.
You may need to change the directory separator if you're not running windows. Also, the conversion is a bit of a hack, but it should work. Out of curiosity, how many packages do you have that manual isn't an option?
public class Converter {
public static void main(String[] args) {
File rootDir = new File(".");
renamePackageToPackageInfo(rootDir);
}
private static void renamePackageToPackageInfo(File dir) {
File[] files = dir.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return "package.html".equals(name);
}
});
for (File file : files) {
convertFile(file);
}
// now recursively rename all the child directories.
File[] dirs = dir.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.isDirectory();
}
});
for (File subdir : dirs) {
renamePackageToPackageInfo(subdir);
}
}
private static void convertFile(File html) {
// determine the FQN package name
String fqpn = getPackageName(html);
// check if package-info.java already exists
File packageInfo = new File(html.getParent(), "package-info.java");
if (packageInfo.exists()) {
System.out.println("package-info.java already exists for package: "+fqpn);
return;
}
// create the i/o streams, and start pumping the data
try {
PrintWriter out = new PrintWriter(packageInfo);
BufferedReader in = new BufferedReader(new FileReader(html));
out.println("/**");
// skip over the headers
while (true) {
String line = in.readLine();
if (line.equalsIgnoreCase("<BODY>"))
break;
}
// now pump the file into the package-info.java file
while (true) {
String line = in.readLine();
if (line.equalsIgnoreCase("</BODY>"))
break;
out.println(" * " + line);
}
out.println("*/");
out.println("package "+fqpn+";");
out.close();
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// queue the package.html file for deletion
//html.deleteOnExit();
}
private static String getPackageName(File file) {
StringBuilder path = new StringBuilder(file.getParent());
// trim the first two characters (./ or .\)
path.delete(0, 2);
// then convert all separators into . (HACK: should use directory separator property)
return path.toString().replaceAll("\\\\", ".");
}
}
The IntelliJ guys have made an intention to do this for all files. It's been resolved and will probably be released in the next IntelliJ release.
To do this in batch mode in IDEA:
In settings, activate the inspection gadget "'package.html' may be converted to 'package-info.java' inspection"
Open a package.html file
You see a banner fix the inspection on top the file
Click on the settings icon at the right on the banner
Select "Run inspection on" >> "Whole project"
Click on "Convert to package-info.java" >> OK
Optionally remove the inappropriate lines (sed -i "/Put #see and #since/d" `find . -name "package-info.java"`)

Categories