I am trying to add a new property to config.properties if it isn't there. Is there any way to do this?
My current config class looks like this:
package com.template;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Properties;
public class Config {
static File folder = new File(System.getProperty("user.home") + "/Documents/Electrocode Productions/template");
public static void add() {
if(!folder.exists()) {
try {
folder.mkdirs();
} catch(SecurityException e) {
Log.error(e);
}
}
Properties config = new Properties();
OutputStream output = null;
Path filePath = Paths.get(folder + "/config.properties");
if(!(filePath == null)) {
try {
output = new FileOutputStream(folder + "/config.properties");
config.setProperty("log", "true");
config.store(output, null);
} catch(IOException e) {
Log.error(e);
} finally {
if(output !=null) {
try {
output.close();
} catch(IOException e) {
Log.error(e);
}
}
}
}
}
public static String get(String value) {
Properties config = new Properties();
InputStream input = null;
try {
input = new FileInputStream(folder + "/config.properties");
config.load(input);
} catch(IOException e) {
Log.error(e);
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return config.getProperty(value).trim();
}
}
This is working, as it won't overwrite the file if you edit it, but if you delete an entry, you need to completely delete the whole file to re-add that entry.
My ultimate goal is for you to be able to close the program, edit the config file, then reopen the config file with the new arguments, but if you delete an argument, it won't crash to program because it relies on an answer from the config file. (I hope that makes sense. It's basically like most video games).
You need to validate the value you get from the Properties before using it. e.g. you can't .trim() a value which wasn't here.
public class Config {
static final File folder = new File(System.getProperty("user.home") + "/Documents/Electrocode Productions/template");
static final File file = new File(folder, "config.properties");
public static void add() throws IOException {
if (file.exists())
return;
// create directories as needed.
folder.mkdirs();
Properties config = new Properties();
config.setProperty("log", "true");
try (OutputStream out = new FileOutputStream(file)) {
config.store(out, null);
}
}
public static String get(String key, String defaultValue) {
if (!file.exists())
return defaultValue;
try (InputStream in = new FileInputStream(file)) {
Properties config = new Properties();
config.load(input);
} catch(IOException e) {
Log.error(e);
return defaultValue;
}
String value = config.getProperty(key);
if (value == null)
return defaultValue;
value = value.trim();
if (value.isEmpty())
return defaultValue;
return value;
}
}
Related
I'm making an application with Google SpeechClient that has the requirements to set a GOOGLE_APPLICATION_CREDENTIALS environment variable that, once set, you can use the voice to text api.
My application is required to run in linux and windows. In linux it runs perfectly, however, on windows, when running the project, it throws an exception com.google.api.gax.rpc.UnavailableException: "io.grpc.StatusRuntimeException: UNAVAILABLE: Credentials failed to obtain metadata" when trying to run this thread
package Controller.Runnables;
import Controller.GUI.VoxSpeechGUIController;
import Model.SpokenTextHistory;
import com.google.api.gax.rpc.ClientStream;
import com.google.api.gax.rpc.ResponseObserver;
import com.google.api.gax.rpc.StreamController;
import com.google.cloud.speech.v1.*;
import com.google.protobuf.ByteString;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.TargetDataLine;
import java.io.IOException;
import java.util.ArrayList;
public class SpeechRecognizerRunnable implements Runnable{
private VoxSpeechGUIController controller;
public SpeechRecognizerRunnable(VoxSpeechGUIController voxSpeechGUIController) {
this.controller = voxSpeechGUIController;
}
#Override
public void run() {
MicrofoneRunnable micrunnable = MicrofoneRunnable.getInstance();
Thread micThread = new Thread(micrunnable);
ResponseObserver<StreamingRecognizeResponse> responseObserver = null;
try (SpeechClient client = SpeechClient.create()) {
ClientStream<StreamingRecognizeRequest> clientStream;
responseObserver =
new ResponseObserver<StreamingRecognizeResponse>() {
ArrayList<StreamingRecognizeResponse> responses = new ArrayList<>();
public void onStart(StreamController controller) {}
public void onResponse(StreamingRecognizeResponse response) {
try {
responses.add(response);
StreamingRecognitionResult result = response.getResultsList().get(0);
// There can be several alternative transcripts for a given chunk of speech. Just
// use the first (most likely) one here.
SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);
String transcript = alternative.getTranscript();
System.out.printf("Transcript : %s\n", transcript);
String newText = SpokenTextHistory.getInstance().getActualSpeechString() + " " + transcript;
SpokenTextHistory.getInstance().setActualSpeechString(newText);
controller.setLabelText(newText);
}
catch (Exception ex){
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
public void onComplete() {
}
public void onError(Throwable t) {
System.out.println(t);
}
};
clientStream = client.streamingRecognizeCallable().splitCall(responseObserver);
RecognitionConfig recognitionConfig =
RecognitionConfig.newBuilder()
.setEncoding(RecognitionConfig.AudioEncoding.LINEAR16)
.setLanguageCode("pt-BR")
.setSampleRateHertz(16000)
.build();
StreamingRecognitionConfig streamingRecognitionConfig =
StreamingRecognitionConfig.newBuilder().setConfig(recognitionConfig).build();
StreamingRecognizeRequest request =
StreamingRecognizeRequest.newBuilder()
.setStreamingConfig(streamingRecognitionConfig)
.build(); // The first request in a streaming call has to be a config
clientStream.send(request);
try {
// SampleRate:16000Hz, SampleSizeInBits: 16, Number of channels: 1, Signed: true,
// bigEndian: false
AudioFormat audioFormat = new AudioFormat(16000, 16, 1, true, false);
DataLine.Info targetInfo =
new DataLine.Info(
TargetDataLine.class,
audioFormat); // Set the system information to read from the microphone audio
// stream
if (!AudioSystem.isLineSupported(targetInfo)) {
System.out.println("Microphone not supported");
System.exit(0);
}
// Target data line captures the audio stream the microphone produces.
micrunnable.targetDataLine = (TargetDataLine) AudioSystem.getLine(targetInfo);
micrunnable.targetDataLine.open(audioFormat);
micThread.start();
long startTime = System.currentTimeMillis();
while (!micrunnable.stopFlag) {
long estimatedTime = System.currentTimeMillis() - startTime;
if (estimatedTime >= 55000) {
clientStream.closeSend();
clientStream = client.streamingRecognizeCallable().splitCall(responseObserver);
request =
StreamingRecognizeRequest.newBuilder()
.setStreamingConfig(streamingRecognitionConfig)
.build();
startTime = System.currentTimeMillis();
} else {
request =
StreamingRecognizeRequest.newBuilder()
.setAudioContent(ByteString.copyFrom(micrunnable.sharedQueue.take()))
.build();
}
clientStream.send(request);
}
} catch (Exception e) {
System.out.println(e);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I've been working hard for hours and have not found a solution that solves my problem.
It is worth mentioning that the environment variable is being set correctly.
Has anyone ever had this problem with Google? What should I do to fix this?
This is my envirounment variable creator:
PS: I`ve already tried use all google alternatives to validate credentials, but all return me errors.
package Controller.Autentication;
import java.io.*;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class GoogleAuthentication {
private static final String GOOGLE_APPLICATION_CREDENTIALS = "GOOGLE_APPLICATION_CREDENTIALS";
private static final String VoxSpeechFolder = ".vox";
private static final String GoogleAuthenticationJsonFile = "VoxAuthentication.json";
public static void setupGoogleCredentials() {
String directory = defaultDirectory();
directory += File.separator+VoxSpeechFolder;
File voxPath = new File(directory);
if (!voxPath.exists()) {
voxPath.mkdirs();
}
ClassLoader classLoader = new GoogleAuthentication().getClass().getClassLoader();
File srcFile = new File(classLoader.getResource(GoogleAuthenticationJsonFile).getFile());
if(srcFile.exists()){
try {
String voxDestPath = defaultDirectory() + File.separator + VoxSpeechFolder +File.separator+ GoogleAuthenticationJsonFile;
File destFile = new File(voxDestPath);
copyFile(srcFile,destFile);
} catch (IOException e) {
e.printStackTrace();
}
}
try {
Map<String,String> googleEnv = new HashMap<>();
String path = defaultDirectory() +File.separator+ VoxSpeechFolder +File.separator+ GoogleAuthenticationJsonFile;
googleEnv.put(GOOGLE_APPLICATION_CREDENTIALS, path);
setGoogleEnv(googleEnv);
} catch (Exception e) {
e.printStackTrace();
}
}
static void copyFile(File sourceFile, File destFile)
throws IOException {
InputStream inStream ;
OutputStream outStream ;
System.out.println(destFile.getPath());
if(destFile.createNewFile()){
inStream = new FileInputStream(sourceFile);
outStream = new FileOutputStream(destFile);
byte[] buffer = new byte[1024];
int length;
while ((length = inStream.read(buffer)) > 0){
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
}
}
static String defaultDirectory()
{
String OS = getOperationSystem();
if (OS.contains("WIN"))
return System.getenv("APPDATA");
else if (OS.contains("MAC"))
return System.getProperty("user.home") + "/Library/Application "
+ "Support";
else if (OS.contains("LINUX")) {
return System.getProperty("user.home");
}
return System.getProperty("user.dir");
}
static String getOperationSystem() {
return System.getProperty("os.name").toUpperCase();
}
protected static void setGoogleEnv(Map<String, String> newenv) throws Exception {
try {
Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
theEnvironmentField.setAccessible(true);
Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null);
env.putAll(newenv);
Field theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment");
theCaseInsensitiveEnvironmentField.setAccessible(true);
Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null);
cienv.putAll(newenv);
} catch (NoSuchFieldException e) {
Class[] classes = Collections.class.getDeclaredClasses();
Map<String, String> env = System.getenv();
for(Class cl : classes) {
if("java.util.Collections$UnmodifiableMap".equals(cl.getName())) {
Field field = cl.getDeclaredField("m");
field.setAccessible(true);
Object obj = field.get(env);
Map<String, String> map = (Map<String, String>) obj;
map.clear();
map.putAll(newenv);
}
}
}
String genv = System.getenv(GOOGLE_APPLICATION_CREDENTIALS);
System.out.println(genv);
}
}
im really struggling one this one. Basically im working with a couple of my classmates to a project where we have to deliver a space wars remake and we implemented a single player mode where you can actually get scores. problem is i can read my file but cannot write on it. ive tryed with all the system i could find online but didn't manage to get the error solved. here is the code of the class that manages the highscore system. i even tryed creating the file with code and tryed deleting it and recreating an empty one. the file is in the home directory of the project right now. the metods readFile and getHighscores work but the check one always gets stuck in the writing part.
the error i get is " Il privilegio richiesto non appartiene al client
[Ljava.lang.StackTraceElement;#6eb60ef7"
which translates in "The requested privilege does not belong to the client"
Keep in mind it's all in a git repository where i should have all the permissions but it's basically the only idea left in my mind.
package controller;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
/**
*the creation of the HighscoreManager class.
*/
public class HighscoreManager {
private static final int LAST_HIGHSCORE_INDEX = 9;
private static final String FILE_NAME = "/Highscores.txt";
private ArrayList<Integer> highscores = new ArrayList<Integer>();
/**
* reads the file and loads the highscore list.
*/
private void readFile() {
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
String s;
highscores.clear();
try {
is = this.getClass().getResourceAsStream(FILE_NAME);
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
while ((s = br.readLine()) != null) {
highscores.add(Integer.parseInt(s));
}
if(br!=null && isr !=null && is!= null) {
br.close();
isr.close();
is.close();
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
/**
* checks if the passed score is an actual highscores.
* #param score
*/
public void checkHighscores(final int score) {
readFile();
File file = new File(FILE_NAME);
boolean newHighscoreFound = false;
for (int i = 0; i < highscores.size(); i++) {
if (score > highscores.get(i)) {
newHighscoreFound = true;
break;
}
}
if (newHighscoreFound) {
highscores.add(LAST_HIGHSCORE_INDEX, score);
Collections.sort(highscores);
Collections.reverse(highscores);
for (int i : highscores) {
System.out.println(i);
}
if(!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter(file);
bw = new BufferedWriter(fw);
for(int i : highscores) {
bw.write(i);
}
} catch(IOException e) {
System.out.println(e.getStackTrace());
} finally {
if(fw != null && bw != null) {
try {
fw.close();
bw.close();
} catch (IOException e) {
System.out.println(e.getStackTrace());
}
}
}
}
}
/**
* returns an array list of strings containing all the current highscores.
* #return toBeReturned
*/
public ArrayList<String> getHighscores() {
ArrayList<String> toBeReturned = new ArrayList<>();
try {
highscores.clear();
readFile();
for (int i : highscores) {
toBeReturned.add(String.valueOf(i));
}
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
System.out.println("There you have your highscores.");
}
return toBeReturned;
}
}
You don't need to access the Class object to load a file (or indeed the associated ClassLoader). Just use normal Java IO.
To read your set of high scores:
highScores = Files.lines(Paths.get(FILE_NAME))
.map(Integer::parseInt)
.collect(Collectors.toList());
To write a new set of high scores:
Files.write(Paths.get(FILE_NAME), highScores.stream()
.map(String::valueOf)
.collect(Collectors.toList()));
(Also, why is this tagged with "git"?)
I am new to java and trying to write an program which will unzip all the password protected zip files in an directory, I am able to unzip all the normal zip files (Without password) but I am not sure how to unzip password protected files.
Note: All zip files have same password
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.model.FileHeader;
import java.util.zip.*;
public class Extraction {
// public Extraction() {
//
// try {
//
// ZipFile zipFile = new
// ZipFile("C:\\Users\\Desktop\\ZipFile\\myzip.zip");
//
// if (zipFile.isEncrypted()) {
//
// zipFile.setPassword("CLAIMS!");
// }
//
// List fileHeaderList = zipFile.getFileHeaders();
//
// for (int i = 0; i < fileHeaderList.size(); i++) {
// FileHeader fileHeader = (FileHeader) fileHeaderList.get(i);
//
// zipFile.extractFile(fileHeader, "C:\\Users\\Desktop\\ZipFile");
// System.out.println("Extracted");
// }
//
// } catch (Exception e) {
// System.out.println("Please Try Again");
// }
//
// }
//
// public static void main(String[] args) {
// new Extraction();
//
// }
// }
public static void main(String[] args) {
Extraction unzipper = new Extraction();
unzipper.unzipZipsInDirTo(Paths.get("C:\\Users\\Desktop\\ZipFile"),
Paths.get("C:\\Users\\Desktop\\ZipFile\\Unziped"));
}
public void unzipZipsInDirTo(Path searchDir, Path unzipTo) {
final PathMatcher matcher = searchDir.getFileSystem().getPathMatcher("glob:**/*.zip");
try (final Stream<Path> stream = Files.list(searchDir)) {
stream.filter(matcher::matches).forEach(zipFile -> unzip(zipFile, unzipTo));
} catch (Exception e) {
System.out.println("Something went wrong, Please try again!!");
}
}
public void unzip(Path zipFile, Path outputPath) {
try (ZipInputStream zis = new ZipInputStream(Files.newInputStream(zipFile))) {
ZipEntry entry = zis.getNextEntry();
while (entry != null) {
Path newFilePath = outputPath.resolve(entry.getName());
if (entry.isDirectory()) {
Files.createDirectories(newFilePath);
} else {
if (!Files.exists(newFilePath.getParent())) {
Files.createDirectories(newFilePath.getParent());
}
try (OutputStream bos = Files.newOutputStream(outputPath.resolve(newFilePath))) {
byte[] buffer = new byte[Math.toIntExact(entry.getSize())];
int location;
while ((location = zis.read(buffer)) != -1) {
bos.write(buffer, 0, location);
}
}
}
entry = zis.getNextEntry();
}
} catch (Exception e1) {
System.out.println("Please try again");
}
}
}
I found the answer I am posting this as there might be someone else who might be looking for the similar answer.
import java.io.File;
import java.util.List;
import javax.swing.filechooser.FileNameExtensionFilter;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.model.FileHeader;
public class SamExtraction {
public static void main(String[] args) {
final FileNameExtensionFilter extensionFilter = new FileNameExtensionFilter("N/A", "zip");
//Folder where zip file is present
final File file = new File("C:/Users/Desktop/ZipFile");
for (final File child : file.listFiles()) {
try {
ZipFile zipFile = new ZipFile(child);
if (extensionFilter.accept(child)) {
if (zipFile.isEncrypted()) {
//Your ZIP password
zipFile.setPassword("MYPASS!");
}
List fileHeaderList = zipFile.getFileHeaders();
for (int i = 0; i < fileHeaderList.size(); i++) {
FileHeader fileHeader = (FileHeader) fileHeaderList.get(i);
//Path where you want to Extract
zipFile.extractFile(fileHeader, "C:/Users/Desktop/ZipFile");
System.out.println("Extracted");
}
}
} catch (Exception e) {
System.out.println("Please Try Again");
}
}
}
}
I am trying to check if a file content is empty or not. I have a source file where the content is empty.
I tried different alternatives.But nothing is working for me.
Here is my code:
Path in = new Path(source);
/*
* Check if source is empty
*/
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(fs.open(in)));
} catch (IOException e) {
e.printStackTrace();
}
try {
if (br.readLine().length() == 0) {
/*
* Empty file
*/
System.out.println("In empty");
System.exit(0);
}
else{
System.out.println("not empty");
}
} catch (IOException e) {
e.printStackTrace();
}
I have tried using -
1. br.readLine().length() == 0
2. br.readLine() == null
3. br.readLine().isEmpty()
All of the above is giving as not empty.And I need to use -
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(fs.open(in)));
} catch (IOException e) {
e.printStackTrace();
}
Instead of new File() etc.
Please advice if I went wrong somewhere.
EDIT
Making little more clear. If I have a file with just whitespaces or
without white space,I am expecting my result as empty.
You could call File.length() (which Returns the length of the file denoted by this abstract pathname) and check that it isn't 0. Something like
File f = new File(source);
if (f.isFile()) {
long size = f.length();
if (size != 0) {
}
}
To ignore white-space (as also being empty)
You could use Files.readAllLines(Path) and something like
static boolean isEmptyFile(String source) {
try {
for (String line : Files.readAllLines(Paths.get(source))) {
if (line != null && !line.trim().isEmpty()) {
return false;
}
}
} catch (IOException e) {
e.printStackTrace();
}
// Default to true.
return true;
}
InputStream is = new FileInputStream("myfile.txt");
if (is.read() == -1) {
// The file is empty!
} else {
// The file is NOT empty!
}
Of course you will need to close the is and catch IOException
You can try something like this:
A Utility class to handle the isEmptyFile check
package com.stackoverflow.answers.mapreduce;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
public class HDFSOperations {
private HDFSOperations() {}
public static boolean isEmptyFile(Configuration configuration, Path filePath)
throws IOException {
FileSystem fileSystem = FileSystem.get(configuration);
if (hasNoLength(fileSystem, filePath))
return false;
return isEmptyFile(fileSystem, filePath);
}
public static boolean isEmptyFile(FileSystem fileSystem, Path filePath)
throws IOException {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(fileSystem.open(filePath)));
String line = bufferedReader.readLine();
while (line != null) {
if (isNotWhitespace(line))
return false;
line = bufferedReader.readLine();
}
return true;
}
public static boolean hasNoLength(FileSystem fileSystem, Path filePath)
throws IOException {
return fileSystem.getFileStatus(filePath).getLen() == 0;
}
public static boolean isWhitespace(String str) {
if (str == null) {
return false;
}
int length = str.length();
for (int i = 0; i < length; i++) {
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
}
public static boolean isNotWhitespace(String str) {
return !isWhitespace(str);
}
}
Class to test the Utility
package com.stackoverflow.answers.mapreduce;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
public class HDFSOperationsTest {
public static void main(String[] args) {
String fileName = "D:/tmp/source/expected.txt";
try {
Configuration configuration = new Configuration();
Path filePath = new Path(fileName);
System.out.println("isEmptyFile: "
+ HDFSOperations.isEmptyFile(configuration, filePath));
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
I looked into at4j and 7-Zip-JBinding (their javadoc and documentation) but they doesn't seem to be able to read without extracting (and get an InputStream from archived file)
Is there any method I'm missing or haven't found ?
a solution other than extracting to a temporary folder to read it
I'm expecting an answer in how to do it in at4j or 7-Zip-JBinding
in other words I want to know how to utilize below mentioned function in at4j or 7-Zip-JBinding
I know java's built in one has getInputStream I'm currently using it this way
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
/**
* get input stream of current file
* #param path path inside zip
* #return InputStream
*/
public InputStream getInputStream(String path){
try {
ZipEntry entry = zipFile.getEntry(path);
if(entry!=null){
return zipFile.getInputStream(entry);
}
return new ByteArrayInputStream("Not Found".getBytes());
} catch (Exception ex) {
//handle exception
}
return null;
}
(^^ zipFile is a ZipFile object)
found the solution using 7-Zip-JBinding
just need to use ByteArrayInputStream ,this so far worked for a small file
pass a archive as argument to get all files inside printed
file ExtractItemsSimple.java
import java.io.IOException;
import java.io.RandomAccessFile;
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 ExtractItemsSimple {
public static void main(String[] args) {
RandomAccessFile randomAccessFile = null;
ISevenZipInArchive inArchive = null;
try {
randomAccessFile = new RandomAccessFile(args[0], "r");
inArchive = SevenZip.openInArchive(null, // autodetect archive type
new RandomAccessFileInStream(randomAccessFile));
ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface();
for (ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
final int[] hash = new int[] { 0 };
if (!item.isFolder()) {
System.out.println(ArchieveInputStreamHandler.slurp(new ArchieveInputStreamHandler(item).getInputStream(),1000));
}
}
} 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);
}
}
}
}
}
file ArchieveInputStreamHandler.java
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import net.sf.sevenzipjbinding.ISequentialOutStream;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.simple.ISimpleInArchiveItem;
public class ArchieveInputStreamHandler {
private ISimpleInArchiveItem item;
private ByteArrayInputStream arrayInputStream;
public ArchieveInputStreamHandler(ISimpleInArchiveItem item) {
this.item = item;
}
public InputStream getInputStream() throws SevenZipException{
item.extractSlow(new ISequentialOutStream() {
#Override
public int write(byte[] data) throws SevenZipException {
arrayInputStream = new ByteArrayInputStream(data);
return data.length; // Return amount of consumed data
}
});
return arrayInputStream;
}
//got from http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string
public static String slurp(final InputStream is, final int bufferSize){
final char[] buffer = new char[bufferSize];
final StringBuilder out = new StringBuilder();
try {
final Reader in = new InputStreamReader(is, "UTF-8");
try {
for (;;) {
int rsz = in.read(buffer, 0, buffer.length);
if (rsz < 0)
break;
out.append(buffer, 0, rsz);
}
}
finally {
in.close();
}
}
catch (UnsupportedEncodingException ex) {
/* ... */
}
catch (IOException ex) {
/* ... */
}
return out.toString();
}
}
Are you looking for http://docs.oracle.com/javase/6/docs/api/java/util/zip/ZipInputStream.html which can extract entries in zip file without extracting it completely.