Create a directory with ./ folder in java on Windows OS - java

I am working on a Java project in which the Tar file has to be created. These tar files are created on Linux OS so the folder structure always as : C:\Users\Admin\Desktop\Tar\My.tar\.\
In this path, the files are kept i.e. if I open My.tar using 7z or anything then I see files within the path : C:\Users\Admin\Desktop\Tar\My.tar\.\
Now on windows, I have written the code to generate tar file with some files. But it does not create folder having ./ I want the same structure to be followed to generate tar so that existing code wor fine.
How to create a directory with ./ - C:\Users\Admin\Desktop\Tar\My.tar\.\
The code to generate tar file is :
FileOutputStream dest = new FileOutputStream(outputTarFileName);
// Create a TarOutputStream
TarOutputStream out = new TarOutputStream(new BufferedOutputStream(dest));
File folder = new File(inputFolder);
File[] filesToTar = new File[folder.listFiles().length];
int index = 0;
for (final File fileEntry : folder.listFiles()) {
filesToTar[index++] = new File((fileEntry.getAbsolutePath()));
}
for (File f : filesToTar) {
out.putNextEntry(new TarEntry(f, f.getName()));
BufferedInputStream origin = new BufferedInputStream(new FileInputStream(f));
int count;
byte data[] = new byte[2048];
while ((count = origin.read(data)) != -1) {
out.write(data, 0, count);
}
out.flush();
origin.close();
}
out.close();
createTarFile("C:\\Users\\Admin\\Desktop\\Tar\\MyDir","C:\\Users\\Admin\\Desktop\\Tar\\\\.\\My.tar");
I tried by creating a directory having such structure :
new File("C:\Users\Admin.000\Desktop\testfolder\./\W").mkdir();
new File("C:\Users\Admin.000\Desktop\testfolder\\.\W").mkdir();
But nothing worked.

Related

How can I zip a directory with java.util.zip? [duplicate]

This question already has answers here:
How to zip the content of a directory in Java
(3 answers)
Closed 1 year ago.
I want to zip a folder into a zip file with java.util.zip tools.
I have already tried to read org.gradle.api.tasks.bundling.Zip in Gradle, but I cannot understand it at all.
Is there any code or opensource third-party tool that can zip a directory tree?
You can try using ZipOutputStream to create zip.
List<String> srcFiles = Arrays.asList("test1.txt", "test2.txt"); // List of all files
FileOutputStream fos = new FileOutputStream("multiCompressed.zip");
ZipOutputStream zipOut = new ZipOutputStream(fos);
for (String srcFile : srcFiles) {
File fileToZip = new File(srcFile);
FileInputStream fis = new FileInputStream(fileToZip);
ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
zipOut.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
fis.close();
}
zipOut.close();
fos.close();
Since you have to zip a folder, you can read all the files inside folder and put inside list(Call method instead of hard coding file names in list ).
Below code I have written to read file from all folder and sub folder, You can make change in logic according to your requirements.
String path = "folderpath"
File dir = new File(path);
List<String> srcFiles = populateFilesList(dir);
private List<String> populateFilesList(File dir) throws IOException {
List filesListInDir = new ArrayList<String>();
File[] files = dir.listFiles();
for (File file : files) {
if (file.isFile())
{
filesListInDir.add(file.getAbsolutePath());
}
else
{
populateFilesList(file);
}
}
return filesListInDir;
}
Please try this and let me know if you face any issue.
What about use this lib Zeroturnaround Zip library
Then you will zip your folder just a one line:
ZipUtil.pack(new File("D:\sourceFolder\"), new File("D:\generatedZipFile.zip"));

Copy file to resource folder in myProject in java - define relative path

I am trying to copy PDF files from any location in computer to resources directory in myProject (to be used later in my project)
I followed all instruction in the following links:
open resource with relative path in java
How to copy file in resource folder in java
How to define a relative path in java
But I am getting always java.lang.NullPointerException
It is clear to me that I have problem with correct relative path.
I am using NetBeans IDE
MyProject/src/main/java/org/company/office/MyClass.java ---> java class
MyProject/src/main/resources/pdf/ ---> here I want to copy the PDF files
How can I define the correct relative path of "pdf" directory inside MyClass.java?
Also what would be the best code for this case
public void copyFile(String fileName, InputStream in) {
ClassLoader loader = Upload.class.getClassLoader();
File file = new File(loader.getResource("resources/pdf/"+ fileName).getFile());
//File file = new File(loader.getResource("pdf/"+ fileName).getFile());
System.out.println("file.getAbsoluteFile() " + file.getAbsoluteFile());
try {
try ( // write the inputStream to a FileOutputStream
OutputStream out = new FileOutputStream(file)) {
int read = 0;
byte[] bytes = new byte[1024];
while ((read = in.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
in.close();
out.flush();
}
System.out.println("New file created!");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}

Getting strange structure file when zipping a directory using Java

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);
}
}

Creating a TAR file using JTar library

I have been trying to create a tar file from JAVA using the JTar library.I am trying to pack two files into one tar file.However the second file doesn't get listed in the created tar.Rather it is showing up as the content of the first file.
My code looks like :
// Output file stream
FileOutputStream dest = new FileOutputStream("C:\\tarFile");
// Create a TarOutputStream
TarOutputStream out = new TarOutputStream(new BufferedOutputStream(dest));
// Files to tar
File[] filesToTar = new File[2];
filesToTar[0] = new File("C:\\tarSample\\File1.txt");
filesToTar[1] = new File("C:\\tarSample\\File2.txt");
for (File f : filesToTar)
{
TarEntry entry = new TarEntry(f);
out.putNextEntry(entry);
BufferedInputStream origin = new BufferedInputStream(new FileInputStream(f));
int count;
byte data[] = new byte[2048];
while ((count = origin.read(data)) != -1)
{
out.write(data, 0, count);
}
out.flush();
origin.close();
}
out.close();
dest.close();
When i open the contents of the tarFile using "cat" command it looks like :
tarSample/File1.txt100644 0 0 10 12301634500 13305 0ustarkumarang 0 0 tarSample/File2.txt100644 0 0 7 12301634511 13276 0ustarkumarang 0 0
If my understanding is correct the tarEntry is getting added to the tar file .However the contents of the files are not getting written.
Any body knows a fix ?
Thanks.
Just change it to
FileOutputStream dest = new FileOutputStream("C:\\tarFile.tar");

Extract a .tar.gz file in java (JSP)

I can't seem to import the packages needed or find any online examples of how to extract a .tar.gz file in java.
What makes it worse is I'm using JSP pages and am having trouble importing packages into my project. I'm copying the .jar's into WebContent/WEB-INF/lib/ and then right clicking on the project and selecting import external jar and importing it. Sometimes the packages resolve, other times they don't. Can't seem to get GZIP to import either. The imports in eclipse for jsp aren't intuitive like they are in normal Java code where you can right click a recognized package and select import.
I've tried the Apache commons library, the ice and another one called JTar. Ice has imported, but I can't find any examples of how to use it?
I guess I need to uncompress the gzipped part first, then open it with the tarstream?
Any help is greatly appreciated.
The accepted answer works fine, but I think it is redundant to have a write to file operation.
You could use something like
TarArchiveInputStream tarInput =
new TarArchiveInputStream(new GZipInputStream(new FileInputStream("Your file name")));
TarArchiveEntry currentEntry = tarInput.getNextTarEntry();
while(currentEntry != null) {
File f = currentEntry.getFile();
// TODO write to file as usual
}
Hope this help.
Maven Repo
Ok, i finally figured this out, here is my code in case this helps anyone in the future.
Its written in Java, using the apache commons io and compress librarys.
File dir = new File("directory/of/.tar.gz/files/here");
File listDir[] = dir.listFiles();
if (listDir.length!=0){
for (File i:listDir){
/* Warning! this will try and extract all files in the directory
if other files exist, a for loop needs to go here to check that
the file (i) is an archive file before proceeding */
if (i.isDirectory()){
break;
}
String fileName = i.toString();
String tarFileName = fileName +".tar";
FileInputStream instream= new FileInputStream(fileName);
GZIPInputStream ginstream =new GZIPInputStream(instream);
FileOutputStream outstream = new FileOutputStream(tarFileName);
byte[] buf = new byte[1024];
int len;
while ((len = ginstream.read(buf)) > 0)
{
outstream.write(buf, 0, len);
}
ginstream.close();
outstream.close();
//There should now be tar files in the directory
//extract specific files from tar
TarArchiveInputStream myTarFile=new TarArchiveInputStream(new FileInputStream(tarFileName));
TarArchiveEntry entry = null;
int offset;
FileOutputStream outputFile=null;
//read every single entry in TAR file
while ((entry = myTarFile.getNextTarEntry()) != null) {
//the following two lines remove the .tar.gz extension for the folder name
String fileName = i.getName().substring(0, i.getName().lastIndexOf('.'));
fileName = fileName.substring(0, fileName.lastIndexOf('.'));
File outputDir = new File(i.getParent() + "/" + fileName + "/" + entry.getName());
if(! outputDir.getParentFile().exists()){
outputDir.getParentFile().mkdirs();
}
//if the entry in the tar is a directory, it needs to be created, only files can be extracted
if(entry.isDirectory){
outputDir.mkdirs();
}else{
byte[] content = new byte[(int) entry.getSize()];
offset=0;
myTarFile.read(content, offset, content.length - offset);
outputFile=new FileOutputStream(outputDir);
IOUtils.write(content,outputFile);
outputFile.close();
}
}
//close and delete the tar files, leaving the original .tar.gz and the extracted folders
myTarFile.close();
File tarFile = new File(tarFileName);
tarFile.delete();
}
}

Categories

Resources