java 如何在java中使用“ls *.c”命令?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15598657/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use "ls *.c" command in java?
提问by Querier
I am trying to print "*.C" files in java
我正在尝试在 java 中打印“*.C”文件
I use the below code
我使用下面的代码
public static void getFileList(){
try
{
String lscmd = "ls *.c";
Process p=Runtime.getRuntime().exec(lscmd);
p.waitFor();
BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=reader.readLine();
while(line!=null)
{
System.out.println(line);
line=reader.readLine();
}
}
catch(IOException e1) {
System.out.println("Pblm found1.");
}
catch(InterruptedException e2) {
System.out.println("Pblm found2.");
}
System.out.println("finished.");
}
P.S:- It is working fine for "ls" command.when I am using "*" in any command, all aren't work. need the replacement of "*" in the command in java.
PS:- 它适用于“ls”命令。当我在任何命令中使用“*”时,都不起作用。需要在java中的命令中替换“*”。
UPDATE
更新
Thanks for your help guys.
谢谢你们的帮助。
Now i need the same result for the comment " ls -d1 $PWD/** "in java. it will list all the directory names with the full path.
现在,我需要对 java 中的注释“ ls -d1 $PWD/** ”获得相同的结果。它将列出所有带有完整路径的目录名称。
Thanks for your time.
谢谢你的时间。
回答by VGR
You might find this more reliable:
您可能会发现这更可靠:
Path dir = Paths.get("/path/to/directory");
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.c")) {
for (Path file : stream) {
// Do stuff with file
}
}
回答by Stephen C
You need to execute a command of the form "bash -c 'ls *.c'" ... because the java exec
methods do not understand '*'
expansion (globbing). (The "bash -c" form ensures that a shell is used to process the command line.)
您需要执行“bash -c 'ls *.c'”形式的命令......因为javaexec
方法不理解'*'
扩展(globbing)。(“bash -c”形式确保使用 shell 来处理命令行。)
However, you can't simply provide the above command as a single String to Runtime.exec(...)
, because exec
also doesn't understand the right way to split acommand string that has quoting in it.
但是,您不能简单地将上述命令作为单个字符串提供给Runtime.exec(...)
,因为exec
也不了解拆分其中包含引号的命令字符串的正确方法。
Therefore, to get exec
to do the right thing, you need to do something like this:
因此,为了exec
做正确的事情,你需要做这样的事情:
String lscmd = "ls *.c";
Process p = Runtime.getRuntime().exec(new String[]{"bash", "-c", lscmd});
In other words, you need to do the argument splitting by hand ...
换句话说,您需要手动进行参数拆分......
It should be noted that this example could also be implemented by using FileMatcher
to perform the "globbing" and assemble the argument list from the results. But is complicated if you are going something other than running ls
... and IMO the complexity is not justified.
需要注意的是,这个例子也可以通过使用FileMatcher
执行“globbing”并从结果中组装参数列表来实现。但是,如果您要进行跑步以外的其他事情,那就很复杂了ls
……而 IMO 的复杂性是不合理的。
回答by Gregory Pakosz
Alternatively, you can use public File[] File.listFiles(FilenameFilter filter)
或者,您可以使用 public File[] File.listFiles(FilenameFilter filter)
File[] files = dir.listFiles(new FilemaneFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".c");
}
}
回答by user000001
The *
is expanded by the shell. So to use it to expand a filename as a glob, you would have to call the ls
command through a shell, e.g. like this:
在*
由外壳扩展。因此,要使用它来将文件名扩展为 glob,您必须ls
通过 shell调用该命令,例如:
String lscmd = " bash -c 'ls *.c' ";
String lscmd = " bash -c 'ls *.c' ";
Edit
编辑
Good point from @Stephen, about exec failing to split the command. To execute the ls -d1 $PWD/*
you can do it like this:
@Stephen 的好点子,关于 exec 未能拆分命令。要执行ls -d1 $PWD/*
你可以这样做:
String lscmd = "ls -d1 $PWD/*";
Process p = Runtime.getRuntime().exec(new String[]{"bash", "-c", lscmd});
回答by corny
The Java way is to use a FilenameFilter
. I adapted a code example from here:
Java 方法是使用FilenameFilter
. 我从这里改编了一个代码示例:
import java.io.File;
import java.io.FilenameFilter;
public class Filter implements FilenameFilter {
protected String pattern;
public Filter (String str) {
pattern = str;
}
public boolean accept (File dir, String name) {
return name.toLowerCase().endsWith(pattern.toLowerCase());
}
public static void main (String args[]) {
Filter nf = new Filter (".c");
// current directory
File dir = new File (".");
String[] strs = dir.list(nf);
for (int i = 0; i < strs.length; i++) {
System.out.println (strs[i]);
}
}
}
update:
更新:
For your update, you could iterate over a new File (".").listFiles();
and issue file.getAbsolutePath()
on each file.
对于您的更新,您可以在每个文件上迭代 anew File (".").listFiles();
和 issue file.getAbsolutePath()
。
回答by Sifeng
One example to list files since Java 7.
自 Java 7 起列出文件的一个示例。
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main {
public static void main(String[] args) {
Path dir = Paths.get("/your/path/");
try {
DirectoryStream<Path> ds = Files.newDirectoryStream(dir, "*.{c}");
for (Path entry: ds) {
System.out.println(entry);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}