1

我已经搜索并找不到我的问题。我已经用 linux 输出 ls -l 保存了文件,其内容是:

drwxr-xr-x  2 usr usr 4096 Jan 20 17:49 file1
drwxrwxr-x  4 usr usr 4096 Jan 20 18:00 file2
drwx------  2 usr usr 4096 Feb  3 08:48 catalog1

例如,我想只留下带有小时的第八列,并切断其余部分。我应该怎么办?我是java和编程的初学者。

4

2 回答 2

1

您可以使用正则表达式来匹配时间戳(因为可以保证类似时间的值不会出现在任何其他字段中)。就像是:

// Populate this with the output of the ls -l command
String input;

// Create a regular expression pattern to match.
Pattern pattern = Pattern.compile("\\d{2}:\\d{2}");

// Create a matcher for this pattern on the input string.
Matcher matcher = pattern.matcher(input);

// Try to find instances of the given regular expression in the input string.    
while (matcher.find()){
  System.out.println(matcher.group());
}

要检索任意列,您可以选择为要检索的任何列编写正则表达式,或者您可能希望仅在空格字符上拆分每一行,然后按索引选择。例如,要获取所有文件大小:

String input;

String[] inputLines = input.split("\n");
for (String inputLine : inputLines) {
  String[] columns = inputLine.split(" ");
  System.out.println(columns[4]); // Where 4 indicates the filesize column
}
于 2013-02-19T20:44:28.750 回答
0

您需要使用StringTokenizer来提取您正在寻找的确切信息。试试下面的代码:

String value =  "drwxr-xr-x  2 usr usr 4096 Jan 20 17:49 file1\n"+
                "drwxrwxr-x  4 usr usr 4096 Jan 20 18:00 file2\n"+
                "drwx------  2 usr usr 4096 Feb  3 08:48 catalog1";
StringBuffer sBuffer = new StringBuffer(10);
StringTokenizer sTokenizer = new StringTokenizer(value,"\n");
while (sTokenizer.hasMoreTokens())
{
    String sValue = sTokenizer.nextToken();
    StringTokenizer sToken = new StringTokenizer(sValue," ");
    int counter = 0;
    while (sToken.hasMoreTokens())
    {
        String token = sToken.nextToken();
        counter++;
        if (counter == 8)//8 is the column that you want to leave.
        {
            sBuffer.append(token+"\n");
            break;
        }
    }           
}
System.out.println(sBuffer.toString());
于 2013-02-19T21:44:03.160 回答