热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何在java中使用“ls*.c”命令?-Howtouse“ls*.c”commandinjava?

Iamtryingtoprint*.Cfilesinjava我想在java中打印“*.C”文件Iusethebelowcode我使用下面的代码publics

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.

P.S: - 它对“ls”命令工作正常。当我在任何命令中使用“*”时,一切都不起作用。需要在java中的命令中替换“*”。

UPDATE

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.

谢谢你的时间。

7 个解决方案

#1


11  

You might find this more reliable:

您可能会发现这更可靠:

Path dir = Paths.get("/path/to/directory");

try (DirectoryStream stream = Files.newDirectoryStream(dir, "*.c")) {
    for (Path file : stream) {
        // Do stuff with file
    }
}

#2


2  

Alternatively, you can use public File[] File.listFiles(FilenameFilter filter)

或者,您可以使用公共File [] File.listFiles(FilenameFilter过滤器)

File[] files = dir.listFiles(new FilemaneFilter() {
  public boolean accept(File dir, String name) {
    return name.endsWith(".c");
  }
}

#3


1  

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 

update:

更新:

For your update, you could iterate over a new File (".").listFiles(); and issue file.getAbsolutePath() on each file.

对于您的更新,您可以迭代一个新文件(“。”)。listFiles();并在每个文件上发出file.getAbsolutePath()。

#4


1  

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 ds = Files.newDirectoryStream(dir, "*.{c}");
            for (Path entry: ds) {
                System.out.println(entry);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

#5


1  

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'”形式的命令...因为java exec方法不理解'*'扩展(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.

但是,您不能简单地将上述命令作为单个String提供给Runtime.exec(...),因为exec也不了解拆分在其中引用的acommand字符串的正确方法。

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的复杂性是不合理的。

#6


1  

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:

*由shell扩展。因此,要使用它将文件名扩展为glob,您必须通过shell调用ls命令,例如喜欢这个:

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});

#7


-1  

I know, it doesn't directly answers your question, but if you can, prefer the OS independent way to list files in directory.

我知道,它并没有直接回答你的问题,但如果可以的话,更喜欢以OS独立的方式列出目录中的文件。

The advantages are - not Unix/Linux specific Doesn't require to spawn the process (its very expensive).

优点是 - 不是Unix / Linux特定的不需要产生进程(它非常昂贵)。

Here you can find an example of how to do this in java:

在这里你可以找到一个如何在java中执行此操作的示例:

List Files in Directory

列出目录中的文件

Hope this helps

希望这可以帮助


推荐阅读
  • 个人学习使用:谨慎参考1Client类importcom.thoughtworks.gauge.Step;importcom.thoughtworks.gauge.T ... [详细]
  • 本文介绍了Swing组件的用法,重点讲解了图标接口的定义和创建方法。图标接口用来将图标与各种组件相关联,可以是简单的绘画或使用磁盘上的GIF格式图像。文章详细介绍了图标接口的属性和绘制方法,并给出了一个菱形图标的实现示例。该示例可以配置图标的尺寸、颜色和填充状态。 ... [详细]
  • Android工程师面试准备及设计模式使用场景
    本文介绍了Android工程师面试准备的经验,包括面试流程和重点准备内容。同时,还介绍了建造者模式的使用场景,以及在Android开发中的具体应用。 ... [详细]
  • 基于Socket的多个客户端之间的聊天功能实现方法
    本文介绍了基于Socket的多个客户端之间实现聊天功能的方法,包括服务器端的实现和客户端的实现。服务器端通过每个用户的输出流向特定用户发送消息,而客户端通过输入流接收消息。同时,还介绍了相关的实体类和Socket的基本概念。 ... [详细]
  • 本文整理了Java中java.lang.NoSuchMethodError.getMessage()方法的一些代码示例,展示了NoSuchMethodErr ... [详细]
  • 纠正网上的错误:自定义一个类叫java.lang.System/String的方法
    本文纠正了网上关于自定义一个类叫java.lang.System/String的错误答案,并详细解释了为什么这种方法是错误的。作者指出,虽然双亲委托机制确实可以阻止自定义的System类被加载,但通过自定义一个特殊的类加载器,可以绕过双亲委托机制,达到自定义System类的目的。作者呼吁读者对网上的内容持怀疑态度,并带着问题来阅读文章。 ... [详细]
  • ***byte(字节)根据长度转成kb(千字节)和mb(兆字节)**parambytes*return*publicstaticStringbytes2kb(longbytes){ ... [详细]
  • 本文整理了Java面试中常见的问题及相关概念的解析,包括HashMap中为什么重写equals还要重写hashcode、map的分类和常见情况、final关键字的用法、Synchronized和lock的区别、volatile的介绍、Syncronized锁的作用、构造函数和构造函数重载的概念、方法覆盖和方法重载的区别、反射获取和设置对象私有字段的值的方法、通过反射创建对象的方式以及内部类的详解。 ... [详细]
  • OpenMap教程4 – 图层概述
    本文介绍了OpenMap教程4中关于地图图层的内容,包括将ShapeLayer添加到MapBean中的方法,OpenMap支持的图层类型以及使用BufferedLayer创建图像的MapBean。此外,还介绍了Layer背景标志的作用和OMGraphicHandlerLayer的基础层类。 ... [详细]
  • 本文介绍了关于Java异常的八大常见问题,包括异常管理的最佳做法、在try块中定义的变量不能用于catch或finally的原因以及为什么Double.parseDouble(null)和Integer.parseInt(null)会抛出不同的异常。同时指出这些问题是由于不同的开发人员开发所导致的,不值得过多思考。 ... [详细]
  • 在Docker中,将主机目录挂载到容器中作为volume使用时,常常会遇到文件权限问题。这是因为容器内外的UID不同所导致的。本文介绍了解决这个问题的方法,包括使用gosu和suexec工具以及在Dockerfile中配置volume的权限。通过这些方法,可以避免在使用Docker时出现无写权限的情况。 ... [详细]
  • JavaSE笔试题-接口、抽象类、多态等问题解答
    本文解答了JavaSE笔试题中关于接口、抽象类、多态等问题。包括Math类的取整数方法、接口是否可继承、抽象类是否可实现接口、抽象类是否可继承具体类、抽象类中是否可以有静态main方法等问题。同时介绍了面向对象的特征,以及Java中实现多态的机制。 ... [详细]
  • Go Cobra命令行工具入门教程
    本文介绍了Go语言实现的命令行工具Cobra的基本概念、安装方法和入门实践。Cobra被广泛应用于各种项目中,如Kubernetes、Hugo和Github CLI等。通过使用Cobra,我们可以快速创建命令行工具,适用于写测试脚本和各种服务的Admin CLI。文章还通过一个简单的demo演示了Cobra的使用方法。 ... [详细]
  • 本文介绍了一种轻巧方便的工具——集算器,通过使用集算器可以将文本日志变成结构化数据,然后可以使用SQL式查询。集算器利用集算语言的优点,将日志内容结构化为数据表结构,SPL支持直接对结构化的文件进行SQL查询,不再需要安装配置第三方数据库软件。本文还详细介绍了具体的实施过程。 ... [详细]
  • 本文介绍了pack布局管理器在Perl/Tk中的使用方法及注意事项。通过调用pack()方法,可以控制部件在显示窗口中的位置和大小。同时,本文还提到了在使用pack布局管理器时,应注意将部件分组以便在水平和垂直方向上进行堆放。此外,还介绍了使用Frame部件或Toplevel部件来组织部件在窗口内的方法。最后,本文强调了在使用pack布局管理器时,应避免在中间切换到grid布局管理器,以免造成混乱。 ... [详细]
author-avatar
mobiledu2502939937
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有