2014-02-17 51 views
-1

我有這種方法接收作爲參數pdfText(這是一個字符串,包含解析後的pdf文件中的文本)和fileName這是我想寫的文本文件找到一個字符串,並返回它後面的文字

但是現在我需要在這個文本中找到單詞「Keywords」,並且只提取它後面的單詞,它們在同一行(直到換行符)。

比如我有一個地方包含以下行

標題一文:東西。

「關鍵詞:計算機,機器人,當然」

標籤:標籤1,標籤2,標籤3。

結果應該是以下列表[「計算機」,「機器人」,「課程」]。

解決問題

所以我搜索如何解決我question..here是一個解決方案,不是很聰明,但它的工作原理:

  //index of first appearence of the word 
      int index = pdfText.indexOf("Keywords"); 

      //string from that to the end 
      String subStr = pdfText.substring(index); 


      //index of first appearence of the new line in the new string 
      int index1 = subStr.indexOf("\n"); 


      //the string we need 
      String theString = subStr.substring(9,index1); 

      System.out.println(theString); 

      //write in the file..use true as parameter for appending text,not overwrite it 
      FileWriter pw = new FileWriter(fileName,true); 
      pw.write(theString); 

      pw.close(); 
+4

請出示一些嘗試!僅僅因爲你發佈了代碼並不意味着你會努力解決你的問題。 –

+3

你可以通過讓其他人做你的工作來獲得A這個任務,但是你會在決賽中得到一個F。 –

+2

提示:研究'String#split()''String#startsWith()' –

回答

2

老實說,這個問題具體情況也是如此。不管:)

寫入文件

String pdfText = "pdfText"; 
String fileLocation = "fileLocation"; 
Writer writer = null; 
try { 
    writer = new BufferedWriter(new OutputStreamWriter(
      new FileOutputStream(fileLocation), "utf-8")); 
    writer.write(pdfText);  // String you want to write (i.e. pdfText) 
} catch (IOException ioe) { 
    ioe.printStackTrace(); 
} finally { 
    try {writer.close();} catch (Exception ex) { ex.printStackTrace(); } 
} 

它總是一個好主意,指定編碼類型。 ( 「UTF-8」)。儘管你的任務可能並不重要。您可能還需要將追加到文件,而不是完全重寫,在這種情況下,您應該爲FileOutputStream使用不同的構造函數,new FileOutputStream(getFileLocation(), true)。至於很多try/catch塊,不要效仿我的例子。這是我如何設法關閉我的資源,因爲日食推薦哈哈。

解析字符串 如果你有一條線,如"Keywords : Computers, Robots, Course"

String str = "Keywords : Computers, Robots, Course"; 
String[] array = str.substring(indexOf(':') + 1).split(","); 
//this array = ["Computers", "Robots", "Course"] 

現在你有一個數組,可以遍歷和寫入/打印出來,但是你會喜歡。

1

你可以使用regex字後提取的話「關鍵詞:」是這樣的:

String regex = ".*Keywords\\s*:(.*)\\n.*"; 

String extractedLine = yourText.replaceAll(regex, "$1"); 

System.out.println(extractedLine); 
相關問題