2013-02-19 86 views
1

我搜索了并找不到我的问题。 我已经保存与Linux输出LS文件-l其内容是:从java中的文件切割柱

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和编程。

回答

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

要检索任意列,你可以选择写哪个列你想找回一个正则表达式,或者您也可以只拆分的空格字符的每一行,然后按索引选择。例如,让所有的的filesizes的:

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 
} 
+0

我已经写了时间的例子,我的意思是我想留下一列(我会选择),例如给出时间。 – wmarchewka 2013-02-19 20:56:03

+0

有关检索任意列的信息,请参阅我的更新回答。 – 2013-02-19 21:13:59

+0

请记住,文件名可能包含几乎任何东西,包括空格,所以第9列一直延伸到行尾,不应分割。 – hyde 2013-02-19 21:44:59

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()); 
+0

谢谢,这正是我需要的! 这是行之有效的,现在我只能一行一行地研究它是如何工作的;) – wmarchewka 2013-02-19 22:09:36

+0

@ user2088689:如果它解决了你的问题,那么标记答案为可接受的。 – 2013-02-20 16:52:27