1

I want, if you try to copy to the directory, a message is displayed and the program shuts down. In the case of a file, display the file size and the time it was last modified. I don't know exactly, how can i show out file size, and last time modified. ..............................................................................................................................................................

import java.io.*;

public class KopeeriFail {

    private static void kopeeri(String start, String end) throws Exception {
        InputStream sisse = new FileInputStream(start);
        OutputStream välja = new FileOutputStream(end);
        byte[] puhver = new byte[1024];
        int loetud = sisse.read(puhver);
        while (loetud > 0) {
            välja.write(puhver, 0, loetud);
            loetud = sisse.read(puhver);
        }
        sisse.close();
        välja.close();
    }

    public static void main(String[] args) throws Exception {
        if (args.length != 1) {
            System.out.println("Did you gave name to the file");
            System.exit(1);
        }
        kopeeri(args[0], args[0] + ".copy");
    }
}
Vlad Paskevits
  • 388
  • 2
  • 12
  • Partial duplicate - [How to get file size](https://stackoverflow.com/questions/2149785/get-size-of-folder-or-file) – Piro Apr 17 '18 at 12:24

1 Answers1

1

You can easily fetch BasicFileAttributes which stores size and last modification timestamp.

public static void main(String[] args) throws IOException {
    if (args.length != 1) {
        System.err.println("Specify file name");
        return;
    }

    Path initial = Paths.get(args[0]);
    if (!Files.exists(initial)){
        System.err.println("Path is not exist");
        return;
    }

    if (Files.isDirectory(initial)) {
        System.err.println("Path is directory");
        return;
    }

    BasicFileAttributes attributes = Files.
            readAttributes(initial, BasicFileAttributes.class);
    System.out.println("Size is " + attributes.size() + " bytes");
    System.out.println("Last modified time " + attributes.lastModifiedTime());

    Files.copy(initial, initial.getParent()
            .resolve(initial.getFileName().toString() + ".copy"));
}

Hope it helps!

Sergey Prokofiev
  • 1,815
  • 1
  • 12
  • 21