2013-02-19 45 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