简体   繁体   中英

zip,move and size of file which is in a server path using java

I have a file in the server, I want to create three java APIs, which will do the below three operations in dependently.

  1. Get the file size
  2. Move a file with different file name to a different server location
  3. Zip the file

In my existing code we are executing Linux commands to perform those operations, unfortunately, Linux commands are not getting executed, this is due to some server/set up issue, so I am forced to use Java commands.(We use JDK 1.6)

I am not a Java developer. I have gone through some of the previously answered questions, but they are not explaining about file in server path. Any help is much appreciated.

To get the file size in bytes:

File file = new File("filename.txt");
long fileSize = file.length();

To move a file you must first copy it and then delete the original:

InputStream  inStream = null;
OutputStream outStream = null;

    try {
        File fromFile = new File("startfolder\\filename.txt");
        File toFile   = new File("endfolder\\filename.txt");

        inStream  = new FileInputStream(fromFile);
        outStream = new FileOutputStream(toFile);

        byte[] buffer = new byte[1024];

        int length;
        while ((length = inStream.read(buffer)) > 0){
            outStream.write(buffer, 0, length);
        }

        inStream.close();
        outStream.close();

        fromFile.delete();

    } catch(IOException e) {
        e.printStackTrace();
    }

To zip a file:

byte[] buffer = new byte[1024];

try {

FileInputStream fileToZip = new FileInputStream("filename.txt");
FileOutputStream fileOutputStream = new FileOutputStream("filename.zip");
ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);

ZipEntry zipEntry= new ZipEntry("filename.txt");
zipOutputStream.putNextEntry(zipEntry);

int len;
while ((len = fileToZip.read(buffer)) > 0) {
    zipOutputStream.write(buffer, 0, len);
}

fileToZip.close();
zipOutputStream.closeEntry();
zipOutputStream.close();

} catch(IOException e) {
   e.printStackTrace();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM