I want to copy file to another directory.I know this has been asked million times,I read tons of answers about this but I just can't seem to make it work.This is the code I am currently using:
copyFile(new File(getClass().getResource("/jars/TurnOffClient.jar").toString()),
new File("C:\\Documents and Settings\\All Users\\Start Menu\\Programs\\Startup\\karioc.jar"));
And this is the method:
public static void copyFile(File sourceFile, File destFile) throws IOException {
if(!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
destination.transferFrom(source, 0, source.size());
}
finally {
if(source != null) {
source.close();
}
if(destination != null) {
destination.close();
}
}
}
This is my dir:
Directories http://imageshack.com/a/img820/6418/5g3m.png
//////////////////////////////////////////////////////////////////////////////////////////
And this is the exception I get:
Standard ways to copy a file don't work because you are trying to copy the file out of the JAR. When you get a file out of a JAR, you can't get a File object for it. You can get a URL, and from that an InputStream.
An existing answer includes code to copy data from one input stream to another. Here it is, adapted for the file inside a JAR:
InputStream in = getClass().getResourceAsStream("/jars/TurnOffClient.jar");
OutputStream out = new FileOutputStream(new File("C:\\Documents and Settings\\All Users\\Start Menu\\Programs\\Startup\\karioc.jar"));
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
in.close();
out.close();
Have you tried using java.nio.Files.copy(); ?
There's built in methods for doing this.
If that doesn't work then go ahead and transfer bytes from a file inputstream to an output file stream.
public void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
As described here: Standard concise way to copy a file in Java?
Related
I want to read data from lets say 4 zip files called zip1, zip2, zip3, zip4. All of these zip files are split from this 1 big zip file called "BigZip". I want to combine the zip files into one and then compare the bytes if the 1 bigzip file matches the size of bytes with the combined zip file of (zip1+zip2+zip3+zip4). I am getting a very small file size when I combine the size of 4 zip files. What am I doing wrong?
Here is my code for the same:
targetFilePath1, targetFilePath2, targetFilePath3, targetFilePath4 belongs to path of 4 zip files.
sourceFilePath is the path to BigZip file
class Test {
public static void main(String args[]) {
ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(sourceBigZip));
readZip(sourceFilePath, targetFilePath1);
readZip(sourceFilePath, targetFilePath2);
readZip(sourceFilePath, targetFilePath3);
readZip(sourceFilePath, targetFilePath4);
outStream.close();
}
static void readZip(String sourceBigZip, String targetFile) throws Exception {
ZipInputStream inStream = new ZipInputStream(new FileInputStream(targetFile));
byte[] buffer = new byte[1024];
int len = inStream.read(buffer);
while (len != -1) {
outStream.write(buffer, 0, len);
len = inStream.read(buffer);
System.out.print(len);
}
inStream.close();
}
}
Create ZipOutputStream once and pass it to readZip() method, like:
public static void main(String args[]) {
ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(sourceFilePath));
readZip(outStream , targetFilePath1);
readZip(outStream , targetFilePath2);
readZip(outStream , targetFilePath3);
readZip(outStream , targetFilePath4);
}
Then you have an error dealing with copying the data from one zip to another...
You need to copy each file in the zip file like this:
static void readZip(ZipOutputStream outStream, String targetFile)
throws Exception {
ZipInputStream inStream = new ZipInputStream(new FileInputStream(
targetFile));
byte[] buffer = new byte[1024];
int len = 0;
for (ZipEntry e; (e = inStream.getNextEntry()) != null;) {
outStream.putNextEntry(e);
while ((len = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, len);
}
}
inStream.close();
}
}
Every time you call new ZipOutputStream, it creates a new empty file, and wipes out everything you have written to it before.
You have to create the stream outside of readZip, and pass it in to each call rather than creating a new stream every time.
I´m trying to implement some "over the air" update mechanism for OSGi bundles. For that, I need to be able to create a jar file from a String (basically the content of the jar file read by JarInputStream). The following example code should illustrate my needs:
//read bundle to be copied!
File originalFile = new File(
"/Users/stefan/Documents/Projects/OSGi/SimpleBundle_1.0.0.201404.jar");
JarInputStream fis = new JarInputStream(new FileInputStream(originalFile));
StringBuilder stringBuilder = new StringBuilder();
int ch;
while ((ch = fis.read()) != -1) {
stringBuilder.append((char) ch);
}
fis.close();
//Create content string
String content = stringBuilder.toString();
if (logger.isInfoEnabled()) {
logger.info(content);
}
//Init new jar input stream
JarInputStream jarInputStream = new JarInputStream(
new ByteArrayInputStream(content.getBytes()));
if (logger.isInfoEnabled()) {
logger.info("Save content to disc!");
}
File newFile = new File(
"/Users/stefan/Documents/Projects/OSGi/equinox/SimpleBundle_1.0.0.201404.jar");
//Init new jar output stream
JarOutputStream fos = new JarOutputStream(
new FileOutputStream(newFile));
if (!newFile.exists()) {
newFile.createNewFile();
}
int BUFFER_SIZE = 10240;
byte buffer[] = new byte[BUFFER_SIZE];
while (true) {
int nRead = jarInputStream.read(buffer, 0,
buffer.length);
if (nRead <= 0)
break;
fos.write(buffer, 0, nRead);
}
//Write content to new jar file.
fos.flush();
fos.close();
jarInputStream.close();
Unfortunately, the created jar file is empty and throws an "Invalid input file" error if I try to open it with JD-GUI. Is it possible to create a jar file from the String "content"?
Best regards and thank you very much
Stefan
Your jar is empty because you do not read anything from the JarInputStream. If you want to read JarInputStream, you should iterate its entries. If you want to change the Manifest, the first entry should be skipped, use the getManifest() of the jarInputStream and the constructor of the JarOutputStream, where Manifest can be specified. Based on your code (no manifest change but plain jar copy):
ZipEntry zipEntry = jarInputStream.getNextEntry();
while (zipEntry != null) {
fos.putNextEntry(zipEntry);
// Simple stream copy comes here
int BUFFER_SIZE = 10240;
byte buffer[] = new byte[BUFFER_SIZE];
int l = jarInputStream.read(buffer);
while(l >= 0) {
fos.write(buffer, 0, l);
l = jarInputStream.read(buffer);
}
zipEntry = jarInputStream.getNextEntry();
}
You only need this if you want to change the content (Manifest or entries) of the JAR file during the copy. Otherwise, simple InputStream and FileOutputStream will do the work (as Tim said).
I'm creating a xlsx using poi and saving it on fileSystem. I need to download the file on a servlet call and due to memory constraints I did not create a xssf workbook object and used the following code instead :
byte[] buf = new byte[1024];
ServletOutputStream sOut = response.getOutputStream();
FileInputStream input = null;
try {
long length = fileToRead.length();
input = new FileInputStream(fileToRead);
while ((input != null) && ((length = input.read(buf)) != -1)) {
sOut.write(buf, 0, (int) length);
}
Where fileToRead is the file present at the file system.
How can I integrate this with How to create a zip file in Java
You could use
ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
....
ze = new ZipEntry("xlsData");
zos.putEntry (ze);
// loop
zos.write(buf, 0, (int) length);
// finally
zos.close();
I need to replace a specific CSS file inside zip archive the file is stored under folders EPUB/styles/stylesheet.css
here is my code(I need to do it in java 6)
public static void main(String[] args) throws IOException {
File newCss=new File("D:\\test\\css\\stylesheet.css");
ZipOutputStream out = new ZipOutputStream(new FileOutputStream
(new File("D:\\test\\css\\edited\\my_book.epub"),true));
out.putNextEntry(new ZipEntry("EPUB/styles/stylesheet.css"));
InputStream in = new FileInputStream(newCss);
byte[] buf = new byte[4096 * 1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.closeEntry();
in.close();
out.close();
System.out.println("Done Replacing entry");
}
}
but on executing this code the whole zip contains only the CSS i replaced all the other contents are lost but the zip shows the same size as before, on extracting the zip i get only the file i replaced.
I have an application where Service A will provide a zipped data to Service B. And service B needs to unzip it.
Service A has an exposes method getStream and it gives ByteArrayInputStream as output and the data init is zipped data.
However passing that to GzipInputStream gives Not in Gzip format exception.
InputStream ins = method.getInputStream();
GZIPInputStream gis = new GZIPInputStream(ins);
This gives an exception. When the file is dumped in Service A the data is zipped. So getInputStream gives the zipped data.
How to process it ans pass it to the GzipInputStream?
Regards
Dheeraj Joshi
If it zipped, then you must use ZipInputstream.
It does depend on the "zip" format. There are multiple formats that have the zip name (zip, gzip, bzip2, lzip) and different formats call for different parsers.
http://en.wikipedia.org/wiki/List_of_archive_formats
http://www.codeguru.com/java/tij/tij0115.shtml
http://docstore.mik.ua/orelly/java-ent/jnut/ch25_01.htm
If you are using zip then try this code:
public void doUnzip(InputStream is, String destinationDirectory) throws IOException {
int BUFFER = 2048;
// make destination folder
File unzipDestinationDirectory = new File(destinationDirectory);
unzipDestinationDirectory.mkdir();
ZipInputStream zis = new ZipInputStream(is);
// Process each entry
for (ZipEntry entry = zis.getNextEntry(); entry != null; entry = zis
.getNextEntry()) {
File destFile = new File(unzipDestinationDirectory, entry.getName());
// create the parent directory structure if needed
destFile.getParentFile().mkdirs();
try {
// extract file if not a directory
if (!entry.isDirectory()) {
// establish buffer for writing file
byte data[] = new byte[BUFFER];
// write the current file to disk
FileOutputStream fos = new FileOutputStream(destFile);
BufferedOutputStream dest = new BufferedOutputStream(fos,
BUFFER);
// read and write until last byte is encountered
for (int bytesRead; (bytesRead = zis.read(data, 0, BUFFER)) != -1;) {
dest.write(data, 0, bytesRead);
}
dest.flush();
dest.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
is.close();
}
public static void main(String[] args) {
UnzipInputStream unzip = new UnzipInputStream();
try {
InputStream fis = new FileInputStream(new File("test.zip"));
unzip.doUnzip(fis, "output");
} catch (IOException e) {
e.printStackTrace();
}
}