How to zip a byte array using ZipFileSystem - java

How to create a zip file with a byte array using ZipFileSystem ?
The example in the Zip File System Provider shows how to zip an existing one, but I don't seem to find a way to create one from in memory byte array.

I didn't realize I was using the same value for the target zip file and the file inside the zip file.
Modifying the original example I have this working:
import java.util.*;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.*;
public class ZipFSPUser {
public static void main(String [] args) throws Throwable {
Map<String, String> env = new HashMap<>();
env.put("create", "true");
// locate file system by using the syntax
// defined in java.net.JarURLConnection
URI uri = URI.create("jar:file:/codeSamples/zipfs/zipfstest.zip");
try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
Path pathInZipfile = zipfs.getPath("/SomeTextFile.txt");
// copy a file into the zip file
Files.write(pathInZipfile, new byte[]{'h', 'i'} );
}
}
}
Now the /codeSamples/zipfs/zipfstest.zip file is created with /SomeTextFile.txt inside and when I unzip it the content is indeed hi

Related

java zip filesystem reading zip entries

SO, from what I've gathered, one is supposed to be able to create a filesystem from a zip from java 7 and beyond. I'm trying this, the ultimate goal is to use the File object and access these files, just as if I accessed an unzipped file.
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.*;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class MainZipTest {
public static void main(String[] args) throws IOException, URISyntaxException {
Map<String, String> env = new HashMap<>();
env.put("read", "true");
File file = new File("C:/pathtoazip/data.zip");
URI uri = file.toURI();
String path = "jar:" + uri;
FileSystem fs = FileSystems.newFileSystem(URI.create(path), env);
for (Path p : fs.getRootDirectories()) {
System.out.println("root" + p);
//says "/"
System.out.println(new File(p.toString()).exists());
for (File f : new File(p.toString()).listFiles())
System.out.println(f.getAbsolutePath());
//lists the contents of my c drive!
}
System.out.println(new File("somefile.txt").exists());
System.out.println(fs.getPath("somefile.txt").toFile().exists());
System.out.println(new File("/somefile.txt").exists());
System.out.println(fs.getPath("/somefile.txt").toFile().exists());
}
}
it all prints "false". What am I doing wrong here? Or am I wrong in my assumption that I can access these files through the File object? If so, how does one access them?
Path was introduced as generalization of File (disk file). A Path can be inside a zip file, an URL, and more.
You can use Files with Path for similar File functionality.
for (Path p : fs.getRootDirectories()) {
System.out.println("root: " + p);
System.out.println(Files.exists(p));
Files.list(p).forEach(f -> System.out.println(f.toAbsolutePath()));
}
Note that a Path, like from a zip will maintain its actual file system view (fs, the zip).
So avoid File.

Create a new file in .zip folder using Scala

I have a requirement where I have to create 1 xml file inside my .zip folder.
Can you please let me know how can I achieve this using java/scala?
Also let me know can I directly update .zip folder Array[Byte] and add extra Array[Byte] for my new xml file ?
If you are using Java 7 and later, then you should use Zip File System
The following code sample shows how to create a zip file system and
copy a file to the new zip file system.
import java.util.*;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.*;
public class ZipFSPUser {
public static void main(String [] args) throws Throwable {
Map<String, String> env = new HashMap<>();
env.put("create", "true");
// locate file system by using the syntax
// defined in java.net.JarURLConnection
URI uri = URI.create("jar:file:/codeSamples/zipfs/zipfstest.zip");
try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
Path externalTxtFile = Paths.get("/codeSamples/zipfs/SomeTextFile.txt");
Path pathInZipfile = zipfs.getPath("/SomeTextFile.txt");
// copy a file into the zip file
Files.copy( externalTxtFile,pathInZipfile,
StandardCopyOption.REPLACE_EXISTING );
}
}
}
This post could help you: Appending files to a zip file with Java

Can a Jar File be updated programmatically without rewriting the whole file?

It is possible to update individual files in a JAR file using the jar command as follows:
jar uf TicTacToe.jar images/new.gif
Is there a way to do this programmatically?
I have to rewrite the entire jar file if I use JarOutputStream, so I was wondering if there was a similar "random access" way to do this. Given that it can be done using the jar tool, I had expected there to be a similar way to do it programmatically.
It is possible to update just parts of the JAR file using Zip File System Provider available in Java 7:
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;
public class ZipFSPUser {
public static void main(String [] args) throws Throwable {
Map<String, String> env = new HashMap<>();
env.put("create", "true");
// locate file system by using the syntax
// defined in java.net.JarURLConnection
URI uri = URI.create("jar:file:/codeSamples/zipfs/zipfstest.zip");
try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
Path externalTxtFile = Paths.get("/codeSamples/zipfs/SomeTextFile.txt");
Path pathInZipfile = zipfs.getPath("/SomeTextFile.txt");
// copy a file into the zip file
Files.copy( externalTxtFile,pathInZipfile,
StandardCopyOption.REPLACE_EXISTING );
}
}
}
Yes, if you use this opensource library you can modify it in this way as well.
https://truevfs.java.net
public static void main(String args[]) throws IOException{
File entry = new TFile("c:/tru6413/server/lib/nxps.jar/dir/second.txt");
Writer writer = new TFileWriter(entry);
try {
writer.write(" this is writing into a file inside an archive");
} finally {
writer.close();
}
}

How to pass path from file to system property of my java class

I have a configuration file and I want to read a path to a file from config file and pass it to system properties of my java class. That's what I want to get from the file:
# path configuration
MyfilePATH="$projectPath/file name"
and that's what I have in my java class:
private static final String FILE_PATH = System.getProperty("FILE_PATH","DEFAULT_PATH");
and I uset the FILE_PATH in my java class. but since I am quite new to java I do not know how to pass the value from config file to my java class.
Any help?
Thanks
System.getProperty will only return some specific properties : http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html
What you want is to read your own property file. This is described here : http://docs.oracle.com/javase/tutorial/essential/environment/properties.html
The general idea will be :
package stack;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class Main {
public static void main(String[] args) throws IOException {
Properties props = new Properties();
FileInputStream in = new FileInputStream("/absolute/path/to/your/yourconfigfile.properties");
props.load(in);
in.close();
String filePath = props.getProperty("MyFilePATH", "WHATEVER-DEFAULT-VALUE-YOU WANT");
System.out.println(filePath);
}
}
However, it's not very clear what you want in your case ; what does the $projectPath thing means to you ? If you want String interpolation (replacing the $projectPath part inside the String with something else), it's a different story.
Use Properties first to load the config file as shown below
Properties prop = new Properties();
// load a properties file
prop.load(new FileInputStream("config.properties"));
Then, to access MyfilePATH from the loaded properties use
String myPath = prop.getProperty("MyfilePATH")

How to copy-paste, and cut-paste file or folder in java?

I made a desktop app in java with netbeans platform. In my app I want to give separate copy-paste and cut-paste option of file or folder.
So how can I do that? I tried Files.copy(new File("D:\\Pndat").toPath(),new File("D:\\212").toPath(), REPLACE_EXISTING);. But I don't get the exact output.
If there any other option then suggest me.
In case of "cut-paste" you can use renameTo() like this:
File source = new File("////////Source path");
File destination = new File("//////////destination path");
if (!destination.exists()) {
source.renameTo(destination);
}
In case of "copy-paste" you need to read in Input and Output stream.
Use FileUtils from apache io and do FileUtils.copyDirectory(sourceDir, destDir);
You can also do the following file operations
writing to a file
reading from a file
make a directory including parent directories
copying files and directories
deleting files and directories
converting to and from a URL
listing files and directories by filter and extension
comparing file content
file last changed date
Download link for apache i/o jar.
I think this question relates to using the system clipboard for copying a file specified in a Java app and using the OS "Paste" function to copy the file to a folder. Here is a short instructional example that will show you how to add a single file to the OS clipboard for later doing an OS "Paste" function. Tweak as necessary and add error/exception checking as needed.
As a secondary, this code also places the file name on the clipboard so you can paste the file name into document editors.
package com.example.charles.clipboard;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
public class JavaToSystemClipboard {
public static void main(final String[] args) throws Exception {
final File fileOut = new File("someFileThatExists");
putFileToSystemClipboard(fileOut);
}
public static void putFileToSystemClipboard(final File fileOut) throws Exception {
final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
final ClipboardOwner clipboardOwner = null;
final Transferable transferable = new Transferable() {
public boolean isDataFlavorSupported(final DataFlavor flavor) {
return false;
}
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] { DataFlavor.javaFileListFlavor, DataFlavor.stringFlavor };
}
public Object getTransferData(final DataFlavor flavor) {
if (flavor.equals(DataFlavor.javaFileListFlavor)) {
final List<String> list = new ArrayList<>();
list.add(fileOut.getAbsolutePath());
return list;
}
if (flavor.equals(DataFlavor.stringFlavor)) {
return fileOut.getAbsolutePath();
}
return null;
}
};
clipboard.setContents(transferable, clipboardOwner);
}
}
You can write things by yourself using FileOutputStream and FileInputStream or you can used Apache Camel.

Categories