Decompress files with .7z extension in java - java

Can someone advice (give example) any appropriate and understandable way how to extract file or files with .7z extension basing upon InputStream. I have been examined the XZ for java api, but couldn't succeed. Waiting for any suggestion.

This code might help you.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;
import net.sf.sevenzipjbinding.ExtractOperationResult;
import net.sf.sevenzipjbinding.ISequentialOutStream;
import net.sf.sevenzipjbinding.ISevenZipInArchive;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
import net.sf.sevenzipjbinding.simple.ISimpleInArchive;
import net.sf.sevenzipjbinding.simple.ISimpleInArchiveItem;
public class unzip {
public static void main(String[] args) {
RandomAccessFile randomAccessFile = null;
ISevenZipInArchive inArchive = null;
try {
randomAccessFile = new RandomAccessFile("oclHashcat-plus-0.14.7z", "r");
inArchive = SevenZip.openInArchive(null, // autodetect archive type
new RandomAccessFileInStream(randomAccessFile));
// Getting simple interface of the archive inArchive
ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface();
System.out.println(" Hash | Size | Filename");
System.out.println("----------+------------+---------");
for (final ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
final int[] hash = new int[] { 0 };
if (!item.isFolder()) {
ExtractOperationResult result;
final long[] sizeArray = new long[1];
result = item.extractSlow(new ISequentialOutStream() {
public int write(byte[] data) throws SevenZipException {
//Write to file
FileOutputStream fos;
try {
File file = new File(item.getPath());
file.getParentFile().mkdirs();
fos = new FileOutputStream(file);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
hash[0] ^= Arrays.hashCode(data); // Consume data
sizeArray[0] += data.length;
return data.length; // Return amount of consumed data
}
});
if (result == ExtractOperationResult.OK) {
System.out.println(String.format("%9X | %10s | %s", //
hash[0], sizeArray[0], item.getPath()));
} else {
System.err.println("Error extracting item: " + result);
}
}
}
} catch (Exception e) {
System.err.println("Error occurs: " + e);
System.exit(1);
} finally {
if (inArchive != null) {
try {
inArchive.close();
} catch (SevenZipException e) {
System.err.println("Error closing archive: " + e);
}
}
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e) {
System.err.println("Error closing file: " + e);
}
}
}
}
}

Related

Java not reading all object from file

So I have a real strange bug, I get my objects into a arraylist, write them out to see if everything is there, everything checks out, i write them down into a file, eveything is there when I open the file, but when i go on to read them some objects are for unknow reasons not read, like that entry isnt exisitng in the file, but I can see in the file that they are there. Anyone know that I'm missing here?
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class ReadWriteTD {
public static void write(ArrayList<Tokendata> list) {
try {
FileOutputStream f = new FileOutputStream(new File("src/resources/TokenProfiles"));
ObjectOutputStream o = new ObjectOutputStream(f);
// Write objects to file
list.forEach(a -> {
try {
o.writeObject(a);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
});
o.close();
f.close();
} catch (FileNotFoundException e) {
System.out.println("File not found");
} catch (IOException e) {
System.out.println("Error initializing stream");
}
}
public static ArrayList<Tokendata> read() {
ArrayList<Tokendata> list = new ArrayList<Tokendata>();
try {
FileInputStream fi = new FileInputStream(new File("src/resources/TokenProfiles"));
ObjectInputStream oi = new ObjectInputStream(fi);
Boolean cond = true;
while(cond){
if(oi.readObject() != null)
list.add((Tokendata) oi.readObject());
else cond=false;
}
oi.close();
fi.close();
}catch(Exception e){
}
//list.forEach(a -> System.out.print(a.toString()));
return list;
}
}
This is the problem:
if(oi.readObject() != null)
list.add((Tokendata) oi.readObject());
That's calling readObject() twice per iteration. The result of the first call is ignored other than to check whether or not it's null. You just want something like:
Object obj;
while ((obj = oi.readObject()) != null) {
list.add((Tokendata) obj);
}
No need for your cond variable, and now you're only calling readObject once per iteration.

Java status 400 for URL

Hello - I'm trying to download a file using Apache commons fileUtils but it always ends up getting a 400 error. The file's URL is valid because I successfully downloaded it many times using the browser. Any ideas?
java.io.IOException: Server returned HTTP response code: 400 for URL:
http://www.nikaia-hosp.gr/img/ΤΕΛΙΚΕΣ ΠΡΟΔΙΑΓΡΑΦΕΣ ΓΙΑ ΥΠΕΡΗΧΟ
ΓΥΝΑΙΚΟΛΟΓΙΚΟ ΜΑΙΕΥΤΙΚΟ ΠΡΟΓΕΝΝΗΤΙΚΟΥ ΕΛΕΓΧΟΥ.pdf at
sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1894)
at
sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492)
at java.net.URL.openStream(URL.java:1045) at
org.apache.commons.io.FileUtils.copyURLToFile(FileUtils.java:1478) at
com.nikaia.main.NikaiaReader.Downloader.download(Downloader.java:17)
at com.nikaia.main.NikaiaReader.Downloader.main(Downloader.java:32)
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.commons.io.FileUtils;
public class Downloader {
public static void download(String url,String filename){
//System.out.println("filename is : "+filename);
try {
// FileUtils.copyURLToFile(new URL(url), new File("C:/downloads/"+filename));
FileUtils.copyURLToFile(new URL(url), new File(PropertyReader.readProperty("ExtractedFilesPath")+"/"+filename));
try {
Thread.sleep(Integer.parseInt(PropertyReader.readProperty("downloadTimeout"))*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String ar[]){
download("http://www.nikaia-hosp.gr/img/ΤΕΛΙΚΕΣ ΠΡΟΔΙΑΓΡΑΦΕΣ ΓΙΑ ΥΠΕΡΗΧΟ ΓΥΝΑΙΚΟΛΟΓΙΚΟ ΜΑΙΕΥΤΙΚΟ ΠΡΟΓΕΝΝΗΤΙΚΟΥ ΕΛΕΓΧΟΥ.pdf","stupid.pdf");
}
}
OK answer found , I checked the encoded browser url and the url that UTF-8 java returns and the difference was that browser had %20 in the url but java had + .
I replaced all + with %20 in java and its working.
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import org.apache.commons.io.FileUtils;
public class Downloader {
public static void download(String url, String filename) {
try {
String base = "http://www.nikaia-hosp.gr/img/";
if (url.contains("http://www.nikaia-hosp.gr/img/")) {
FileUtils.copyURLToFile(
new URL(base + URLEncoder.encode(url.replace(base, ""), "UTF-8").replaceAll("\\+", "%20")),
new File(PropertyReader.readProperty("ExtractedFilesPath") + "/" + filename));
} else {
FileUtils.copyURLToFile(new URL(url),
new File(PropertyReader.readProperty("ExtractedFilesPath") + "/" + filename));
}
try {
Thread.sleep(Integer.parseInt(PropertyReader.readProperty("downloadTimeout")) * 1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String ar[]) {
download(
"http://www.nikaia-hosp.gr/img/ΤΕΛΙΚΕΣ ΠΡΟΔΙΑΓΡΑΦΕΣ ΓΙΑ ΥΠΕΡΗΧΟ ΓΥΝΑΙΚΟΛΟΓΙΚΟ ΜΑΙΕΥΤΙΚΟ ΠΡΟΓΕΝΝΗΤΙΚΟΥ ΕΛΕΓΧΟΥ.pdf",
"stupid.pdf");
}
}
this work for me, the problem was the encoding, you need encode only the path of the url
InputStream in = new URL(url).openStream();
FileUtils.copyToFile(in,new File(filename));
first open a Stream with the url and then copy this stream data in a file. using copyToFile method
your code will be
public static void download(String url,String filename){
try {
//changed this 2 lines
URL encodeUrl = new URL(UriUtils.encodePath(url, "UTF-8"));
InputStream in = encodeUrl.openStream();
FileUtils.copyToFile(in, new File(PropertyReader.readProperty("ExtractedFilesPath")+"/"+filename));
try {
Thread.sleep(Integer.parseInt(PropertyReader.readProperty("downloadTimeout"))*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String ar[]){
download("http://www.nikaia-hosp.gr/img/ΤΕΛΙΚΕΣ ΠΡΟΔΙΑΓΡΑΦΕΣ ΓΙΑ ΥΠΕΡΗΧΟ ΓΥΝΑΙΚΟΛΟΓΙΚΟ ΜΑΙΕΥΤΙΚΟ ΠΡΟΓΕΝΝΗΤΙΚΟΥ ΕΛΕΓΧΟΥ.pdf","stupid.pdf");
}
and add this dependency to your pom.xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
this does the magic.
UriUtils.encodePath(host+path, "UTF-8");

How to write into the USB (External storage)

I am trying to copy a file from my computer to USB in java. The problem is, the code creates a file on the Usb but the content of the file is not copied from source to destination(computer to usb). How can i do that?
I want the filename R.java to be copied into the usb as system.txt.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class R {
private static File to;
public static void main(String[] args) {
// current working dir where there is file u want to replicate
File f = new File("." + "/R.java");
// destination location
File so = new File("/media");
for (File s : so.listFiles()) {
String r = s.getName();
to = new File("/media/" + r + "/system.txt");
if (!to.exists()) {
try {
to.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out
.print(to.getName() + " " + e.getMessage() + "\n");
}
}
if (f.exists()) {
FileChannel is = null;
FileChannel os = null;
try {
is = new FileInputStream(f).getChannel();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
os = new FileOutputStream(to).getChannel();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
os.transferFrom(is, 0, is.size());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
I am on LINUX machine

Java read file with scanner

I have this code that have some methods for creating a file, adding data to the file and then read the file with scanner.
My problem is that I want it to run my three methods at once but it stops
at the method number two and does not read the file with readFile() method
createFile();
addResponses(file);
readFile(file);
I can not run these three together. It does not read the file. But if I take
the other methods away like this
//createFile();
//addResponses(file);
readFile(file);
Then the read file method works.
I hope you did understand my problem. Is there something wrong with my code?
import java.io.*;
import java.util.Formatter;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Main {
static Formatter f;
static String sträng = " ";
static BufferedWriter output;
static File file;
static int nummer = 1;
static int counter = 0;
static private StringBuffer strBuff;
static InputStream is;
static FileWriter fw;
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
createFile();
addResponses(file);
readFile(file);
}
public static int addResponse() {
if (nummer == 6) {
try {
output.close();
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
System.exit(0);
}
sträng = JOptionPane.showInputDialog("Numbers 1-5 to number " + nummer");
try {
return Integer.parseInt(sträng);
} catch (NumberFormatException f) {
return 6;
}
}
public static File createFile() {
try {
file = new File("numbers.txt");
f = new Formatter(file);
f.close();
} catch (SecurityException se) {
System.err.println("You dont have write access to this file");
System.exit(1);
} catch (Exception ex) {
System.err.println("Error opening or creating file");
System.exit(1);
}
return file;
}
public static void readFile(File x) {
try {
x = new File("numbers.txt");
Scanner in = new Scanner(x);
while (in.hasNextLine()) {
System.out.println(in.nextLine());
}
in.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public static void addResponses(File f) throws IOException {
try {
fw = new FileWriter(f, true);
output = new BufferedWriter(fw);
int x = addResponse();
if (nummer == 1) {
output.write(String.format("%s%10s\n", "Rating", " Frequency"));
}
while (x != -1) {
if (x > 0 && x < 6) {
output.write(String.format("%s%10s\n", nummer, sträng));
nummer++;
} else {
JOptionPane.showMessageDialog(null, "Input only numbers between 1-5");
}
x = addResponse();
}
output.close();
} catch (IOException io) {
JOptionPane.showMessageDialog(null, "Wrong");
}
}
}
after playing around with the code, I found out that in your addResponse() method , you have added System.exit(0); so baiscally program was terminating. I've change it to return -1 and it seems to be working.
by the way, this is a very bad coding practice, each method should do stuff seperately regarless of other method. in your case everything is so integerated that is very hard to root the problem. I recommend you looking at some coding convention.
this is how addResponse() method should be working:
public static File createFile() {
try {
file = new File("numbers.txt");
f = new Formatter(file);
f.close();
} catch (SecurityException se) {
System.err.println("You dont have write access to this file");
System.exit(1);
} catch (Exception ex) {
System.err.println("Error opening or creating file");
System.exit(1);
}
return file;
}

decompress a .z file in java [duplicate]

Can someone advice (give example) any appropriate and understandable way how to extract file or files with .7z extension basing upon InputStream. I have been examined the XZ for java api, but couldn't succeed. Waiting for any suggestion.
This code might help you.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;
import net.sf.sevenzipjbinding.ExtractOperationResult;
import net.sf.sevenzipjbinding.ISequentialOutStream;
import net.sf.sevenzipjbinding.ISevenZipInArchive;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
import net.sf.sevenzipjbinding.simple.ISimpleInArchive;
import net.sf.sevenzipjbinding.simple.ISimpleInArchiveItem;
public class unzip {
public static void main(String[] args) {
RandomAccessFile randomAccessFile = null;
ISevenZipInArchive inArchive = null;
try {
randomAccessFile = new RandomAccessFile("oclHashcat-plus-0.14.7z", "r");
inArchive = SevenZip.openInArchive(null, // autodetect archive type
new RandomAccessFileInStream(randomAccessFile));
// Getting simple interface of the archive inArchive
ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface();
System.out.println(" Hash | Size | Filename");
System.out.println("----------+------------+---------");
for (final ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
final int[] hash = new int[] { 0 };
if (!item.isFolder()) {
ExtractOperationResult result;
final long[] sizeArray = new long[1];
result = item.extractSlow(new ISequentialOutStream() {
public int write(byte[] data) throws SevenZipException {
//Write to file
FileOutputStream fos;
try {
File file = new File(item.getPath());
file.getParentFile().mkdirs();
fos = new FileOutputStream(file);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
hash[0] ^= Arrays.hashCode(data); // Consume data
sizeArray[0] += data.length;
return data.length; // Return amount of consumed data
}
});
if (result == ExtractOperationResult.OK) {
System.out.println(String.format("%9X | %10s | %s", //
hash[0], sizeArray[0], item.getPath()));
} else {
System.err.println("Error extracting item: " + result);
}
}
}
} catch (Exception e) {
System.err.println("Error occurs: " + e);
System.exit(1);
} finally {
if (inArchive != null) {
try {
inArchive.close();
} catch (SevenZipException e) {
System.err.println("Error closing archive: " + e);
}
}
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e) {
System.err.println("Error closing file: " + e);
}
}
}
}
}

Categories

Resources