简体   繁体   中英

Java invoke listing files from command line

I try to invoke file listing from command line using java. it looks like that:

try {
p=Runtime.getRuntime().exec("cmd.exe /k dir /b /S /a-d \"C:\\Image");
    } catch (IOException e1) {
        e1.printStackTrace();
    } 
    BufferedReader reader=new BufferedReader(
    new InputStreamReader(p.getInputStream())
    ); 

and then I ready line by line... and this is working.

But I want to get also filename and filesize, so I try to invoke like that:

try {
p=Runtime.getRuntime().exec("cmd.exe for %F in (\"C:\\Image*\") do @echo %~zF  %F");
    } catch (IOException e1) {
        e1.printStackTrace();
    } 
    BufferedReader reader=new BufferedReader(
    new InputStreamReader(p.getInputStream())
    ); 

and this return me only two lines: Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved. which is not a filename and filesize;)

is this is possible to get those infomarion (filesize) by invoking cmd from java code?

use the File class to get the file size and file name:

public void listFilesForFolder(File folder) {
    for (File fileEntry : folder.listFiles()) {
        if (fileEntry.isDirectory()) {
            listFilesForFolder(fileEntry);
        } else {
            System.out.println(fileEntry.getName());
            System.out.println(fileEntry.getTotalSpace());

        }
    }
}

The answer to your question as it stands is that you're looking in C:\\Image* , and I think you meant to look at C:\\Image\\* . Try changing the relevant bit to

(\"C:\\Image\\*\")

(You might need *.* , depending on whether Windows has caught up with the rest of the world recently.)

But you really shouldn't be doing it like this at all. The right way to do it is this:

try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*")) {
    for (Path entry: stream) {
        System.out.println(entry.toString()+" has size "+Files.size(entry)
             +" and date "+Files.getLastModifiedTime(entry).toString());
    }
} catch (DirectoryIteratorException ex) {
    // do some error processing
}

I can't see any reason to think that a shell command will be any faster. It's doing the same disk I/O.

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