在java中从文件中删除列

时间:2013-02-19 20:38:47

标签: java

我搜索过,找不到我的问题。 我用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和编程的初学者。

2 个答案:

答案 0 :(得分: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
}

答案 1 :(得分: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());