I am new to java and I am having trouble specifying where to save the folder after I zipped it. It always go to the project workspace that I am creating. I want it to be saved in the path
"C:\\Users\\win8.1\\Desktop\\AES"
Here is the code:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipUtils
{
private List<String> fileList;
private static final String OUTPUT_ZIP_FILE = "Folder.zip";
private static final String SOURCE_FOLDER = "C:\\Users\\win8.1\\Desktop\\AES\\SAMPLEPATH"; // SourceFolder path
public ZipUtils()
{
fileList = new ArrayList<String>();
}
public static void main(String[] args)
{
ZipUtils appZip = new ZipUtils();
appZip.generateFileList(new File(SOURCE_FOLDER));
appZip.zipIt(OUTPUT_ZIP_FILE);
}
public void zipIt(String zipFile)
{
byte[] buffer = new byte[1024];
String source = "";
FileOutputStream fos = null;
ZipOutputStream zos = null;
try
{
try
{
source = SOURCE_FOLDER.substring(SOURCE_FOLDER.lastIndexOf("\\") + 1, SOURCE_FOLDER.length());
}
catch (Exception e)
{
source = SOURCE_FOLDER;
}
fos = new FileOutputStream(zipFile);
zos = new ZipOutputStream(fos);
System.out.println("Output to Zip : " + zipFile);
FileInputStream in = null;
for (String file : this.fileList)
{
System.out.println("File Added : " + file);
ZipEntry ze = new ZipEntry(source + File.separator + file);
zos.putNextEntry(ze);
try
{
in = new FileInputStream(SOURCE_FOLDER + File.separator + file);
int len;
while ((len = in.read(buffer)) > 0)
{
zos.write(buffer, 0, len);
}
}
finally
{
in.close();
}
}
zos.closeEntry();
System.out.println("Folder successfully compressed");
}
catch (IOException ex)
{
ex.printStackTrace();
}
finally
{
try
{
zos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
public void generateFileList(File node)
{
// add file only
if (node.isFile())
{
fileList.add(generateZipEntry(node.toString()));
}
if (node.isDirectory())
{
String[] subNote = node.list();
for (String filename : subNote)
{
generateFileList(new File(node, filename));
}
}
}
private String generateZipEntry(String file)
{
return file.substring(SOURCE_FOLDER.length() + 1, file.length());
}
}
I got the code here. Thank you in advance!
There is no problem. Just write
private static final String OUTPUT_ZIP_FILE = "C:\\Users\\win8.1\\Desktop\\AES\\Folder.zip";
private static final String SOURCE_FOLDER = "C:\\Users\\win8.1\\Desktop\\AES\\SAMPLEPATH";
Related
I am trying to zip two folder with each having some text file. Now I want that 2 folders should zip as one folder with their respective files.
I tried to code, but there is some issue with the zip.
The Zip contains multiple folders.
Here is the code:
package com.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipFolders
{
public static void main(String[] args) throws IOException
{
List<String> listOfDir = new ArrayList<String>();
String dirpath1 = "/home/administrator/Documents/ZipTest/folder1";
String dirpath2 = "/home/administrator/Documents/ZipTest/folder2";
String ZipName = "/home/administrator/Documents/ZipTest/output.zip";
listOfDir.add(dirpath1);
listOfDir.add(dirpath2);
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ZipName));
zipDirectories(listOfDir,zos);
zos.close();
System.out.println("Zip Created Successfully");
}
private static void zipDirectories(List<String> listOfDir, ZipOutputStream zos) {
for(String dirPath:listOfDir){
try {
zipdirectory(dirPath, zos);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void zipdirectory(String dirpath, ZipOutputStream zos) throws IOException
{
File f = new File(dirpath);
String[] flist = f.list();
for(int i=0; i<flist.length; i++)
{
File ff = new File(f,flist[i]);
if(ff.isDirectory())
{
zipdirectory(ff.getPath(),zos);
continue;
}
String filepath = ff.getPath();
ZipEntry entries = new ZipEntry(filepath);
zos.putNextEntry(entries);
FileInputStream fis = new FileInputStream(ff);
int buffersize = 1024;
byte[] buffer = new byte[buffersize];
int count;
while((count = fis.read(buffer)) != -1)
{
zos.write(buffer,0,count);
}
fis.close();
}
}
}
But the output I am getting is not as expected I am getting folder 1 & folder 2
like
output.zip//home/administrator/Documents/ZipTest/ then here we are having our folder1 & folder2.
My expected output was :- inside the zip only the two folders should exist with there files.
Your zipdirectory method is used recursive here:
if(ff.isDirectory())
{
zipdirectory(ff.getPath(),zos);
continue;
}
That is creating all the folders you see.
You need to distiquish between the path of each file/dir and the path of the zip entry:
private static void zipDirectories(List<String> listOfDir, ZipOutputStream zos) {
for(String dirPath:listOfDir){
try {
File dir = new File(dirPath);
zipdirectory(dir, dir.getName(), zos);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void zipdirectory(File dir, String dirpath,
ZipOutputStream zos) throws IOException
{
String[] flist = dir.list();
for(int i=0; i<flist.length; i++)
{
String fn = flist[i];
String fp = dirpath == null || dirpath.isEmpty()
? fn : dirpath + "/" + fn;
File ff = new File(dir, fn);
if(ff.isDirectory())
{
zipdirectory(ff, fp,zos);
continue;
}
ZipEntry entries = new ZipEntry(fp);
zos.putNextEntry(entries);
FileInputStream fis = new FileInputStream(ff);
int buffersize = 1024;
byte[] buffer = new byte[buffersize];
int count;
while((count = fis.read(buffer)) != -1)
{
zos.write(buffer,0,count);
}
fis.close();
}
}
Copy , Paste the Code and Run it for the result :-
package com.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipFolders
{
public static void main(String[] args) throws IOException
{
List<String> listOfDir = new ArrayList<String>();
String dirpath1 = "/home/administrator/Documents/ZipTest/folder1";
String dirpath2 = "/home/administrator/Documents/ZipTest/folder2";
String ZipName = "/home/administrator/Documents/ZipTest/output.zip";
listOfDir.add(dirpath1);
listOfDir.add(dirpath2);
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ZipName));
zipDirectories(listOfDir,zos);
zos.close();
System.out.println("Zip Created Successfully");
}
private static void zipDirectories(List<String> listOfDir, ZipOutputStream zos) {
for(String dirPath:listOfDir){
try {
zipdirectory(dirPath, zos);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void zipdirectory(String dirpath, ZipOutputStream zos) throws IOException
{
File f = new File(dirpath);
String[] flist = f.list();
for(int i=0; i<flist.length; i++)
{
File ff = new File(f,flist[i]);
if(ff.isDirectory())
{
zipdirectory(ff.getPath(),zos);
continue;
}
String fileName = ff.getPath().substring(ff.getPath().lastIndexOf('/'));
String folder = dirpath.substring(dirpath.lastIndexOf('/')+1);
ZipEntry entries = new ZipEntry(folder+fileName);
zos.putNextEntry(entries);
FileInputStream fis = new FileInputStream(ff);
int buffersize = 1024;
byte[] buffer = new byte[buffersize];
int count;
while((count = fis.read(buffer)) != -1)
{
zos.write(buffer,0,count);
}
fis.close();
}
}
}
I have a piece of code that iterates over all the files in a directory.
But I am stuck now at reading the content of the file into a String object.
public String filemethod(){
if (path.isDirectory()) {
files = path.list();
String[] ss;
for (int i = 0; i < files.length; i++) {
ss = files[i].split("\\.");
if (files[i].endsWith("txt"))
System.out.println(files[i]);
}
}
return String.valueOf(files);
}
Faced with a similar problem and wrote a code a while back. This will read the content of all files of a directory.
May require adjustments based on your file directories but its tried and tested code.Hope this helps :)
package FileHandling;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
public class BufferedInputStreamExample {
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
public void readFile(File folder) {
ArrayList<File> myFiles = listFilesForFolder(folder);
for (File f : myFiles) {
String path = f.getAbsolutePath();
//Path of the file(Optional-You can know which file's content is being printed)
System.out.println(path);
File infile = new File(path);
try {
fis = new FileInputStream(infile);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while (dis.available() != 0) {
String line = dis.readLine();
System.out.println(line);
}
} catch (IOException e) {
} finally {
try {
fis.close();
bis.close();
dis.close();
} catch (Exception ex) {
}
}
}
}
public ArrayList<File> listFilesForFolder(final File folder){
ArrayList<File> myFiles = new ArrayList<File>();
for (File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
myFiles.addAll(listFilesForFolder(fileEntry));
} else {
myFiles.add(fileEntry);
}
}
return myFiles;
}
}
Main method
package FileHandling;
import java.io.File;
public class Main {
public static void main(String args[]) {
//Your directory here
final File folder = new File("C:\\Users\\IB\\Documents\\NetBeansProjects\\JavaIO\\files");
BufferedInputStreamExample bse = new BufferedInputStreamExample();
bse.readFile(folder);
}
}
I would use following code:
public static Collection<File> allFilesInDirectory(File root) {
Set<File> retval = new HashSet<>();
Stack<File> todo = new Stack<>();
todo.push(root);
while (!todo.isEmpty()) {
File tmp = todo.pop();
if (tmp.isDirectory()) {
for (File child : tmp.listFiles())
todo.push(child);
} else {
if (isRelevantFile(tmp))
retval.add(tmp);
}
}
return retval;
}
All you need then is a method that defines what files are relevant for your usecase (for instance txt)
public static boolean isRelevantFile(File tmp) {
// get the extension
String ext = tmp.getName().contains(".") ? tmp.getName().substring(tmp.getName().lastIndexOf('.') + 1) : "";
return ext.equalsIgnoreCase("txt");
}
Once you have all the files, you can easily get all the text with a little hack in Scanner
public static String allText(File f){
// \\z is a virtual delimiter that marks end of file/string
return new Scanner(f).useDelimiter("\\z").next();
}
So now, using these methods you can easily extract all the text from an entire directory.
public static void main(String[] args){
File rootDir = new File(System.getProperty("user.home"));
String tmp = "";
for(File f : allFilesInDirectory(rootDir)){
tmp += allText(f);
}
System.out.println(tmp);
}
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
public class ReadDataFromFiles {
static final File DIRECTORY = new File("C:\\myDirectory");
public static void main(String[] args) throws IOException {
StringBuilder sb = new StringBuilder();
//append content of each file to sb
for(File f : getTextFiles(DIRECTORY)){
sb.append(readFile(f)).append("\n");
}
System.out.println(sb.toString());
}
// get all txt files from the directory
static File[] getTextFiles(File dir){
FilenameFilter textFilter = (File f, String name) -> name.toLowerCase().endsWith(".txt");
return dir.listFiles(textFilter);
}
// read the content of a file to string
static String readFile(File file) throws IOException{
return new String(Files.readAllBytes(Paths.get(file.getAbsolutePath())), StandardCharsets.UTF_8);
}
}
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");
}
}
}
}
package com.otp.util;
import java.io.FileWriter; import java.io.IOException; import
java.text.SimpleDateFormat; import java.util.Date;
import com.otp.servlets.MessageServlet;
public class CDRWriter {
public FileWriter fileWriter = null;
static int lineCounter = 0;
static String fileName = null;
public void writeCDR(String cdrData) throws IOException {
if(lineCounter == 0){
fileName = createFile();
}else if(lineCounter>500){
String temp=fileName;
fileName = createFile();
lineCounter=0;
Runtime rt = Runtime.getRuntime();
String zipCmd="7z a "+"\""+MessageServlet.filePath+temp+".7z"+"\""+" "+"\""+MessageServlet.filePath+temp+"\"";
System.out.println("zipCmd = "+zipCmd);
rt.exec(zipCmd);
//rt.exec("del "+MessageServlet.filePath+temp);
}
System.out.println("cdr data = "+cdrData);
try {
if(lineCounter == 0){
fileWriter = new FileWriter(MessageServlet.filePath+fileName);
}else{
fileWriter = new FileWriter(MessageServlet.filePath+fileName,true);
}
System.out.println("cdr after if else condition ="+cdrData);
fileWriter.write(cdrData.toString());
System.out.println("cdr after write method ="+cdrData);
fileWriter.write("\r\n");
fileWriter.flush();
//fileWriter.close();
lineCounter++;
System.out.println("CDRWriter : lineCounter = "+lineCounter); } catch (IOException e) {
e.printStackTrace();
}
}// end of WriterCDR method
public String createFile() throws IOException {
SimpleDateFormat sdf = new
SimpleDateFormat("dd-MM-yyyy-HH-mm-ss");
String fileName ="GSMS_CDR_"+ sdf.format(new Date())+".txt" ;
return fileName;
}// end of the createFile method
}// end of CDRWriter class
I would do something like that:
import java.io.*;
import SevenZip.Compression.LZMA.*;
public class Create7Zip
{
public static void main(String[] args) throws Exception
{
// file to compress
File inputToCompress = new File(args[0]);
BufferedInputStream inputStream = new BufferedInputStream(new java.io.FileInputStream(inputToCompress));
// archive
File compressedOutput = new File(args[1] + ".7z");
BufferedOutputStream outputStream = new BufferedOutputStream(new java.io.FileOutputStream(compressedOutput));
Encoder encoder = new Encoder();
encoder.SetAlgorithm(2);
encoder.SetDictionarySize(8388608);
encoder.SetNumFastBytes(128);
encoder.SetMatchFinder(1);
encoder.SetLcLpPb(3,0,2);
encoder.SetEndMarkerMode(false);
encoder.WriteCoderProperties(outputStream);
long fileSize;
fileSize = inputToCompress.length();
for (int i = 0; i < 8; i++)
{
outputStream.write((int) (fileSize >>> (8 * i)) & 0xFF);
}
encoder.Code(inputStream, outputStream, -1, -1, null);
// free resources
outputStream.flush();
outputStream.close();
inputStream.close();
}
}
The SKD for the SevenZip packages come from the offical SKD. Download it here ;).
Disclaimer: I believe, I found that snippet a while ago on the net...but I don't found the source anymore.
Serializing data through
try {
FileOutputStream fileOut = new FileOutputStream(
"C:\\Users\\saikiran\\Documents\\NetBeansProjects\\FTP\\reg.ser", true);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(r);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/reg.ser");
pr.println("Registered Successfully ");
} catch (IOException i) {
i.printStackTrace();
}
and while Deserializing not getting entire file objects only getting single object i.e starting object only .
FileInputStream fileIn = new FileInputStream("C:\\Users\\saikiran\\Documents\\NetBeansProjects\\FTP\\reg.ser");
ObjectInputStream in = null;
while (fileIn.available() != 0) {
in = new ObjectInputStream(fileIn);
while (in != null && in.available() != 0) {
r = (Registration) in.readObject();
System.out.println("Logged in :" + "User name :" + r.u + "Password " + r.p);
if (r.u.equals(ur) && r.p.equals(ps)) {
System.out.println("Logged in :" + "User name :" + r.u + "Password " + r.p);
pr.println("Display");
}
}
}
I have created the working sample for you .
My POJO serializable class will be ,
import java.io.Serializable;
public class Pojo implements Serializable{
String name;
String age;
String qualification;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getQualification() {
return qualification;
}
public void setQualification(String qualification) {
this.qualification = qualification;
}
}
My main class will be,
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
public class Serialization {
/**
* #param args
*/
public static final String FILENAME = "F:\\test\\cool_file.ser";
public static void main(String[] args) throws IOException, ClassNotFoundException {
FileOutputStream fos = null;
//ObjectOutputStream oos = null;
try {
fos = new FileOutputStream(FILENAME);
//oos = new ObjectOutputStream(fos);
/* for (String s : test.split("\\s+")) {
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(s);
}*/
for(int i=0;i<10;i++){
ObjectOutputStream oos = new ObjectOutputStream(fos);
Pojo pojo = new Pojo();
pojo.setName("HumanBeing - "+i);
pojo.setAge("25 - "+i);
pojo.setQualification("B.E - "+i);
oos.writeObject(pojo);
}
} finally {
if (fos != null)
fos.close();
}
List<Object> results = new ArrayList<Object>();
FileInputStream fis = null;
//ObjectInputStream ois = null;
try {
fis = new FileInputStream(FILENAME);
//ois = new ObjectInputStream(fis);
while (true) {
ObjectInputStream ois = new ObjectInputStream(fis);
results.add(ois.readObject());
}
} catch (EOFException ignored) {
// as expected
} finally {
if (fis != null)
fis.close();
}
System.out.println("results = " + results);
for (int i=0; i<results.size()-1; i++) {
System.out.println(((Pojo)results.get(i)).getName()+ " "+((Pojo)results.get(i)).getAge()+ " "+((Pojo)results.get(i)).getQualification());
}
}
}
Hope it helps.