热门标签 | 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

希望这可以帮助


推荐阅读
  • 本文介绍了Java调用Windows下某些程序的方法,包括调用可执行程序和批处理命令。针对Java不支持直接调用批处理文件的问题,提供了一种将批处理文件转换为可执行文件的解决方案。介绍了使用Quick Batch File Compiler将批处理脚本编译为EXE文件,并通过Java调用可执行文件的方法。详细介绍了编译和反编译的步骤,以及调用方法的示例代码。 ... [详细]
  • Android源码深入理解JNI技术的概述和应用
    本文介绍了Android源码中的JNI技术,包括概述和应用。JNI是Java Native Interface的缩写,是一种技术,可以实现Java程序调用Native语言写的函数,以及Native程序调用Java层的函数。在Android平台上,JNI充当了连接Java世界和Native世界的桥梁。本文通过分析Android源码中的相关文件和位置,深入探讨了JNI技术在Android开发中的重要性和应用场景。 ... [详细]
  • Java太阳系小游戏分析和源码详解
    本文介绍了一个基于Java的太阳系小游戏的分析和源码详解。通过对面向对象的知识的学习和实践,作者实现了太阳系各行星绕太阳转的效果。文章详细介绍了游戏的设计思路和源码结构,包括工具类、常量、图片加载、面板等。通过这个小游戏的制作,读者可以巩固和应用所学的知识,如类的继承、方法的重载与重写、多态和封装等。 ... [详细]
  • 个人学习使用:谨慎参考1Client类importcom.thoughtworks.gauge.Step;importcom.thoughtworks.gauge.T ... [详细]
  • 本文介绍了Swing组件的用法,重点讲解了图标接口的定义和创建方法。图标接口用来将图标与各种组件相关联,可以是简单的绘画或使用磁盘上的GIF格式图像。文章详细介绍了图标接口的属性和绘制方法,并给出了一个菱形图标的实现示例。该示例可以配置图标的尺寸、颜色和填充状态。 ... [详细]
  • 本文整理了Java面试中常见的问题及相关概念的解析,包括HashMap中为什么重写equals还要重写hashcode、map的分类和常见情况、final关键字的用法、Synchronized和lock的区别、volatile的介绍、Syncronized锁的作用、构造函数和构造函数重载的概念、方法覆盖和方法重载的区别、反射获取和设置对象私有字段的值的方法、通过反射创建对象的方式以及内部类的详解。 ... [详细]
  • 微信官方授权及获取OpenId的方法,服务器通过SpringBoot实现
    主要步骤:前端获取到code(wx.login),传入服务器服务器通过参数AppID和AppSecret访问官方接口,获取到OpenId ... [详细]
  • ShiftLeft:将静态防护与运行时防护结合的持续性安全防护解决方案
    ShiftLeft公司是一家致力于将应用的静态防护和运行时防护与应用开发自动化工作流相结合以提升软件开发生命周期中的安全性的公司。传统的安全防护方式存在误报率高、人工成本高、耗时长等问题,而ShiftLeft提供的持续性安全防护解决方案能够解决这些问题。通过将下一代静态代码分析与应用开发自动化工作流中涉及的安全工具相结合,ShiftLeft帮助企业实现DevSecOps的安全部分,提供高效、准确的安全能力。 ... [详细]
  • 使用freemaker生成Java代码的步骤及示例代码
    本文介绍了使用freemaker这个jar包生成Java代码的步骤,通过提前编辑好的模板,可以避免写重复代码。首先需要在springboot的pom.xml文件中加入freemaker的依赖包。然后编写模板,定义要生成的Java类的属性和方法。最后编写生成代码的类,通过加载模板文件和数据模型,生成Java代码文件。本文提供了示例代码,并展示了文件目录结构。 ... [详细]
  • 流数据流和IO流的使用及应用
    本文介绍了流数据流和IO流的基本概念和用法,包括输入流、输出流、字节流、字符流、缓冲区等。同时还介绍了异常处理和常用的流类,如FileReader、FileWriter、FileInputStream、FileOutputStream、OutputStreamWriter、InputStreamReader、BufferedReader、BufferedWriter等。此外,还介绍了系统流和标准流的使用。 ... [详细]
  • 本文介绍了解决Netty拆包粘包问题的一种方法——使用特殊结束符。在通讯过程中,客户端和服务器协商定义一个特殊的分隔符号,只要没有发送分隔符号,就代表一条数据没有结束。文章还提供了服务端的示例代码。 ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • Java学习笔记之面向对象编程(OOP)
    本文介绍了Java学习笔记中的面向对象编程(OOP)内容,包括OOP的三大特性(封装、继承、多态)和五大原则(单一职责原则、开放封闭原则、里式替换原则、依赖倒置原则)。通过学习OOP,可以提高代码复用性、拓展性和安全性。 ... [详细]
  • VSCode快速查看函数定义和代码追踪方法详解
    本文详细介绍了在VSCode中快速查看函数定义和代码追踪的方法,包括跳转到定义位置的三种方式和返回跳转前的位置的快捷键。同时,还介绍了代码追踪插件的使用以及对符号跳转的不足之处。文章指出,直接跳转到定义和实现的位置对于程序员来说非常重要,但需要语言本身的支持。以TypeScript为例,按下F12即可跳转到函数的定义处。 ... [详细]
  • springboot启动不了_Spring Boot + MyBatis 多模块搭建教程
    作者:枫本非凡来源:www.cnblogs.comorzlinp9717399.html一、前言1、创建父工程最近公司项目准备开始重构,框 ... [详细]
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社区 版权所有