how to give the password protection to Zip folder in java? - java

I need to set password protection for Zip folder via java, not for zip folder files. Without password i should not be able to open the Zip folder.
This is the code i found from google.
public static void encrypt(String key, InputStream is, OutputStream os)
throws Throwable {encryptOrDecrypt(key, Cipher.ENCRYPT_MODE, is, os);
}

Done using winzipaes1.0.1.jar...
Sample Code...
import java.io.File;
import java.io.IOException;
import de.idyl.winzipaes.AesZipFileEncrypter;
import de.idyl.winzipaes.impl.AESEncrypterBC;
public class Practice1Main {
public static void main(String[]args) throws IOException{
File aNewZipFile = new File("src.zip");
File existingUnzippedFile = new File("src.txt");
AESEncrypterBC encrypter = new AESEncrypterBC();
encrypter.init("password", 0); // The 0 is keySize, it is ignored for AESEncrypterBC
AesZipFileEncrypter zipEncrypter = new AesZipFileEncrypter(aNewZipFile, encrypter);
zipEncrypter.add(existingUnzippedFile, "src.txt", "password");
zipEncrypter.close();
}
}

The only free library I know of that does this is winzipaes. It has an Apache licence.
Google Code project page => https://code.google.com/p/winzipaes/
Maven Repo Link => http://mvnrepository.com/artifact/de.idyl/winzipaes

Related

Java Creating copy of file before uploading to AWS cloud

I have an image in a directory.
I want to make a copy of that image with a different name without doing harm to the original image in the same directory.
So there will be two same images in one folder with a different name.
I want a basic code like I tried -
File source = new File("resources/"+getImage(0));
File dest = new File("resources/");
source.renameTo("resources/"+getImage(0)+);
try {
FileUtils.copyDirectory(source, dest);
} catch (IOException e) {
e.printStackTrace();
}
When I upload the same image to the Amazon server multiple times in automation and then it starts giving issue to upload.
So we want to upload a mirror copy of image everytime.
In eclipse generally have resources folder. I want to make copy of a original image every-time before we upload and delete it after upload.
Kindly suggest some approach
You can just copy the file and use StandardCopyOption.COPY_ATTRIBUTES
public static final StandardCopyOption COPY_ATTRIBUTES
Copy attributes to the new file.
Files.copy(Paths.get(//path//to//file//and//filename),
Paths.get(//path//to//file//and//newfilename), StandardCopyOption.COPY_ATTRIBUTES);
Not a perfect solution, but Instead of handling pop-up box we can directly force file path into the form: [I have used date-stamp for creating new filenames but some different logic could also be used viz- Random String appender etc.]
import org.junit.jupiter.api.Test;
import java.io.*;
import java.nio.file.Files;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Upload {
private static final String SRC_RESOURCES_FILE_PATH = System.getProperty("user.dir")+"/src/resources/";
File s1 = new File(SRC_RESOURCES_FILE_PATH+"Img1.png");
File s2 = new File(SRC_RESOURCES_FILE_PATH+"Img"+getDateStamp()+".png");
#Test
public void uploadFunction() throws IOException {
copyFileUsingJava7Files(s1,s2);
}
private String getDateStamp(){
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
return dateFormat.format(date).toString();
}
private static void copyFileUsingJava7Files(File source, File dest)
throws IOException {
Files.copy(source.toPath(), dest.toPath());
}
}

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 do I use Java to launch a local HTML page that uses Javascript to load a local json file and display its contents?

I have a java application that reports on the up/down status of several websites and creates a .json file with the data. I have an HTML page that uses javascript to take a .json file and display a nice little grid with red or green lights telling you if a website is up or down. I have no idea how to make the java app tell the html page exactly what the .json file is named (i create a new timestamped .json file every app run). Is there any way to pass a parameter or something to the HTML page on load (currently using Desktop.getDesktop().browse(URI.create("file://blah");), or am I stuck to overwriting my .json file every time I run the app?
How about using a query parameter? Like file://blah.html?json=foo.json Or a fragment: file://blah.html#foo.json.
You could create a tiny local server and register the url /json to any file you want:
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
public class main {
static String readFile(String path, Charset encoding) throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
public static void main(String[] args) throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/", new IndexHandler());
server.createContext("/json", new JsonHandler());
server.start();
}
static class IndexHandler implements HttpHandler {
#Override
public void handle(HttpExchange httpExchange) throws IOException {
String response = readFile("index.html", StandardCharsets.UTF_8);
httpExchange.sendResponseHeaders(200, response.length());
OutputStream os = httpExchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
static class JsonHandler implements HttpHandler {
#Override
public void handle(HttpExchange httpExchange) throws IOException {
String response = readFile("whatEverJsonYouWant.json", StandardCharsets.UTF_8);
httpExchange.sendResponseHeaders(200, response.length());
OutputStream os = httpExchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}
Now the JS can be changed to fetch /json

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.

How to give FTP address in java?

I have written the code which downloads the file from FTP server. Since I have my FTP server locally and I want to access like "ftp://localhost/alfresco". It was alfresco's FTP.
I have the following Code
public class FtpTransfer {
public static final void main(String[] args)
{
FTPClient ftp = new FTPClient();
FileOutputStream br = null;
try
{
ftp.connect("ftp://localhost/alfresco");
ftp.login("admin", "admin");
String file = "KPUB//Admin//TMM//Pickup//TMM_TO_ARTESIA_06152010220246.xml";
br = new FileOutputStream("file");
ftp.retrieveFile("/"+file, br);
System.out.println("Downloaded...");
}
catch(IOException exception) {
System.out.println("Error : "+exception);
}
}
}
The following exception occurs.
Error : java.net.UnknownHostException: ftp://localhost/alfresco
Please let me know how should I give the FTP Host Address?
FTPClient f = new FTPClient();
f.connect("localhost");
f.login(username, password);
FTPFile[] files = listFiles(directory);
Also See
Article from JavaWorld
JavaDoc
Here is an example demonstrating connection to a server, changing present working directory, listing files in a directory and downloading a file to some specified directory.
package test;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
public class FtpTransfer {
public static final void main(String[] args) throws SocketException, IOException {
FTPClient ftp = new FTPClient();
ftp.connect("ftp.somedomain.com"); // or "localhost" in your case
System.out.println("login: "+ftp.login("username", "pass"));
ftp.changeWorkingDirectory("folder/subfolder/");
// list the files of the current directory
FTPFile[] files = ftp.listFiles();
System.out.println("Listed "+files.length+" files.");
for(FTPFile file : files) {
System.out.println(file.getName());
}
// lets pretend there is a JPEG image in the present folder that we want to copy to the desktop (on a windows machine)
ftp.setFileType(FTPClient.BINARY_FILE_TYPE); // don't forget to change to binary mode! or you will have a scrambled image!
FileOutputStream br = new FileOutputStream("C:\\Documents and Settings\\casonkl\\Desktop\\my_downloaded_image_new_name.jpg");
ftp.retrieveFile("name_of_image_on_server.jpg", br);
ftp.disconnect();
}
}
Try remove protocol ("ftp://") from your url.
And please, look at the example.
The FTPClient.connect() method takes the name of a server, not a URL. Try:
ftp.connect("localhost");
Also, you may need to put alfresco somewhere else. If it's part of the file path,
String file = "alfresco/KPUB//Admin//TMM//Pickup//TMM_TO_ARTESIA_06152010220246.xml";

Categories