I need to copy a .jar file (which is a resource in my project) from a separate runnable jar to the startup folder in windows. Here's the code I have so far.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class Installer {
public static void main(String[] args) throws IOException
{
InputStream source = Installer.class.getResourceAsStream("prank.jar");
byte[] buffer = new byte[source.available()];
source.read(buffer);
File targetFile = new File(System.getProperty("user.home") + File.separator + "AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\prank.jar");
OutputStream outStream = new FileOutputStream(targetFile);
outStream.write(buffer);
outStream.close();
}
}
My problem is that after the jar file is copied, it is corrupt (although the size of the original and the copy are the same.) Any thoughts on how to do this and have a runnable jar at the end of the process?
Refer to InputStream#available does not work.
The following line
byte[] buffer = new byte[source.available()];
is not correct, as available only return estimate of the size, the jar will be corrupted when estimate is different with actual. (Example from Java – Write an InputStream to a File) seems incorrect as I can't find any reference that guarantee correctness of available for FileInputStream.
Solution from How to convert InputStream to File in Java is more robust,
private static void copyInputStreamToFile(InputStream inputStream, File file)
throws IOException {
try (FileOutputStream outputStream = new FileOutputStream(file)) {
int read;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
// commons-io
//IOUtils.copy(inputStream, outputStream);
}
}
You can consider to use
IOUtils#copy(InputStream, OutputStream)
Files#copy(InputStream, Path, CopyOption...) suggested by Holger for jdk 1.7 or above
Try this -
Path source = Paths.get("location1/abc.jar");
Path destination = Paths.get("location2/abc.jar");
try {
Files.copy(source, destination);
} catch(FileAlreadyExistsException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Related
I've followed several articles to create a zip file using java ZipOutputStream class. The zip is created but I cannot open it. On my Mac I'm receiving this message when I open it with the unzip command :
End-of-central-directory signature not found. Either this file is not
a zipfile, or it constitutes one disk of a multi-part archive. In the
latter case the central directory and zipfile comment will be found on
the last disk(s) of this archive.
unzip: cannot find zipfile
directory in one of /Users/xxxx/Downloads/iad.zip or
/Users/xxxx/Downloads/iad.zip.zip, and cannot find /Users/xxxx/Downloads/iad.zip.ZIP, period.
My java class :
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static java.util.Arrays.stream;
#Slf4j
#UtilityClass
public class ZipCreator {
public byte[] compressAll(String... files) throws IOException {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zipOut = new ZipOutputStream(baos)) {
stream(files)
.forEach(file -> addToZip(zipOut, file));
return baos.toByteArray();
}
}
private static void addToZip(ZipOutputStream zipOut, String file) {
File fileToZip = new File(file);
try (FileInputStream fis = new FileInputStream(fileToZip.getCanonicalFile())) {
zipOut.putNextEntry(new ZipEntry(fileToZip.getName()));
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
} catch (IOException e) {
log.error("Error when adding file {} to zip", file, e);
}
}
}
Doas anyone have an idea to get this zip open ?
You forgot to call closeEntry(). And you should call close() for ZipOutputStream before baos.toByteArray():
public static byte[] compressAll(String... files) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ZipOutputStream zipOut = new ZipOutputStream(baos)) {
stream(files).forEach(file -> addToZip(zipOut, file));
}
return baos.toByteArray();
}
private static void addToZip(ZipOutputStream zipOut, String file) {
File fileToZip = new File(file);
try (FileInputStream fis = new FileInputStream(fileToZip.getCanonicalFile())) {
zipOut.putNextEntry(new ZipEntry(fileToZip.getName()));
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
zipOut.closeEntry();
} catch (IOException e) {
log.error("Error when adding file {} to zip", file, e);
}
}
For ByteArrayOutputStream you must close ZipOutputStream before retrieve byte array from ByteArrayOutputStream.
For FileOutputStream is the same. You must close ZipOutputStream before closing FileOutputStream. Note that the close methods of resources are called in the opposite order of their creation.
public static void compressAll(String... files) throws IOException {
try (FileOutputStream fos = new FileOutputStream("test.zip");
ZipOutputStream zipOut = new ZipOutputStream(fos)) {
stream(files).forEach(file -> addToZip(zipOut, file));
}
}
I made a Program which moves all files of a folder to another folder but when I'm executing the Program it shows me java.io.FileNotFound Exception and Access is denied
I tried to fix this error but it is still giving me the same error.
What am I doing wrong?
I have also attached the screenshot of Error I am getting.
when I checked the properties of the folder it was read-only, I changed but still, the Issue Persists
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MoveFile
{
public static void main(String\[\] args)
{
InputStream inStream = null;
OutputStream outStream = null;
try{
File afile =new File("C:\\Users\\admin\\Desktop\\A");
File bfile =new File("C:\\Users\\admin\\Desktop\\B");
inStream = new FileInputStream(afile);
outStream = new FileOutputStream(bfile);
byte\[\] buffer = new byte\[1024\];
int length;
while ((length = inStream.read(buffer)) > 0){
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
afile.delete();
System.out.println("File Moved!");
}catch(IOException e){
e.printStackTrace();
}
}
}
I expect the Files of folder A to move in Folder B.
according to your question description , you try to move all file of a folder to another folder...
to do this you can use this code ....
public static void main(String[] args) throws IOException {
String from = "C:/Users/Infra/Desktop/PBL/A";
String to = "C:/Users/Infra/Desktop/PBL/B";
File folder = new File(from);
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
Path temp = Files.move(Paths.get(from +"/"+ file.getName()),
Paths.get(to +"/"+ file.getName()));
}
}
On renaming and moving a file using java code,the contents of the file is removed.How to rename and move a file using java code without erasing the content
Please use below code, it can rename and copy the file into different folder
package han.code.development;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileRenameandMove
{
public static void main(String[] args) throws IOException
{
File file=new File("D:\\Haneef\\Stackoverflow\\files.txt");
FileReader fileR=new FileReader(file);
BufferedReader bufferedReader=new BufferedReader(fileR);
String str=bufferedReader.readLine();
FileWriter fileW=new FileWriter(new File("D:\\Haneef\\Stackoverflow\\Move\\File1.txt"));
fileW.write(str);
fileW.close();
}
}
try{
File afile =new File("C:\\Users\\Jen\\Downloads\\usage.csv");
File bfile =new File("C:\\Users\\Jen\\Desktop\\BJ\\");
inStream = new FileInputStream(afile);
outStream = new FileOutputStream(bfile + "\\"+ dd.get(j).getText()+ "_March _2018.csv");
Thread.sleep(1000);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = inStream.read(buffer)) > 0){
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
// if file copied successfully then delete the original file
afile.delete();
System.out.println("File moved successfully");
}catch(IOException e){
e.printStackTrace();
}
}
How to create zip inside zip file
enter image description here
got bellow Error:
D:\sagar\my work\Package Maker\DirectoryStruct>java zipStructure
java.io.FileNotFoundException: Additional_Sub_Folder\Additional_file.zip (The sy
stem cannot find the path specified)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:221)
at java.io.FileOutputStream.<init>(FileOutputStream.java:110)
at zipStructure.main(zipStructure.java:22)
D:\sagar\my work\Package Maker\DirectoryStruct> that is Additional_sub_folder and Digital_sub_folder. inside Additional_sub_folder 1 zip file created(Additional_file.zip),inside that zip 2 folder are created like xml folder and pdf folder
and inside Digital_sub_folder create Artical_sub_folder,and inside Artical_sub_folder 3 new folder are created that is xml folder,pdf folder and Graphics folder. i try it be below java code but not works properly,please help to create the this structure.
import java.io.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class zipStructure {
public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream("main.zip");
ZipOutputStream zos = new ZipOutputStream(fos);
zos.putNextEntry(new ZipEntry("Additional_Sub_Folder/"));
zos.putNextEntry(new ZipEntry("Digital_Sub_Folder/"));
FileOutputStream fos1 = new FileOutputStream("Additional_Sub_Folder/Additional_file.zip");
ZipOutputStream zos1 = new ZipOutputStream(fos1);
/*zos1.putNextEntry(new ZipEntry("Additional_file.zip/xml/"));
zos1.putNextEntry(new ZipEntry("Additional_file.zip/pdf/"));*/
zos1.putNextEntry(new ZipEntry("Additional_file1.zip/xml/"));
zos1.putNextEntry(new ZipEntry("Additional_file1.zip/pdf/"));
zos1.close();
fos1.close();
zos.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void addToZipFile(String fileName, ZipOutputStream zos) throws FileNotFoundException, IOException {
System.out.println("Writing '" + fileName + "' to zip file");
File file = new File(fileName);
FileInputStream fis = new FileInputStream(file);
ZipEntry zipEntry = new ZipEntry(fileName);
zos.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zos.write(bytes, 0, length);
}
zos.closeEntry();
fis.close();
}
}
[1]: http://i.stack.imgur.com/TNA8b.jpg
I did not have the problem with the zip-I/O, I had the FileNotFoundException with every type of I/O that uses the fileSystem.
What helped for me was, if you're working with eclipse, that there is function like "refresh project" or something like this. Everytime I had problems with I/O, that worked.
I have tried many examples from the same question that has already been asked including:
IOUtils.copy();
(copy is a non-existent method)
Files.copy(source, target, REPLACE_EXISTING);
(REPLACE_EXISTING "Cannot find Symbol")
FileUtils.copyFile();
(FileUtils doesn't exist)
The problems with using them are in brackets.
Here is the code for the most repeated method for copying:
import static java.nio.file.Files;
public void Install()
{
CrtFol();
CrtImgFol();
CrtSaveFol();
CrtSaveFile();
open.runmm();
//I have added the import for "Files"
Files.copy(img1, d4, REPLACE_EXISTING);
//Compiler says "Cannot find symbol" when I go over REPLACE_EXISTING
//img1 is a File and d4 is a File as a directory
}
Are there any other ways to copy or a way to fix the one above?
With Java 7's standard library, you can use java.nio.file.Files.copy(Path source, Path target, CopyOption... options). No need to add additional dependencies or implement your own.
try {
Files.copy( Paths.get( sFrom ),
Paths.get( sTo ),
StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
// Handle exception
}
Not sure if Java actually has anything to copy a file. The simplest way would be to convert the file into a byte stream and then write this stream to another file. Something like this:
InputStream inStream = null;
OutputStream outStream = null;
File inputFile =new File("inputFile.txt");
File outputFile =new File("outputFile.txt");
inStream = new FileInputStream(inputFile);
outStream = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int fileLength;
while ((fileLength = inStream.read(buffer)) > 0){
outStream.write(buffer, 0, fileLength );
}
inStream.close();
outStream.close();
where inputFile is the file being copied from, and outputFile is the name of the copy.
I use this code:
import java.io.*;
public class CopyTest {
public CopyTest() {
}
public static void main(String[] args) {
try {
File stockInputFile = new File("C://test.txt");
File StockOutputFile = new File("C://output.txt");
FileInputStream fis = new FileInputStream(stockInputFile);
FileOutputStream fos = new FileOutputStream(StockOutputFile);
int count = 0;
while((count = fis.read()) > -1){
fos.write(count);
}
fis.close();
fos.close();
} catch (FileNotFoundException e) {
System.err.println("FileStreamsReadnWrite: " + e);
} catch (IOException e) {
System.err.println("FileStreamsReadnWrite: " + e);
}
}
}
Use this code to upload file, I am working on SpringBoot...
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
#Component
public class FileUploadhelper {
public final String uploadDirectory = "D:\\SpringBoot Project\\BootRestBooks\\src\\main\\resources\\static\\image";
public boolean uploadFile(MultipartFile mf) {
boolean flag = false;
try {
Files.copy(mf.getInputStream(), Paths.get(uploadDirectory + "\\" + mf.getOriginalFilename()), StandardCopyOption.REPLACE_EXISTING);
flag = true;
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
}