2013-07-02 133 views
0

我正在學習中文。 我有光學字符識別器的iPhone應用程序,可以捕獲翻譯解釋的格式如下:(字符TAB發音TAB定義)將新行添加到.txt文件

淫穢TAB yin2hui4 TAB淫穢;色情;淫穢

網站TAB wang3zhan4 TAB網站

專項TAB zhuan1xiang4 TAB ATTR。專項

但燒錄卡的應用程序,我需要用這種格式:(文字NEWLINE NEWLINE語音清晰度)

淫穢

yin2hui4

淫褻物品;色情;淫穢

網站

wang3zhan4

<計算>網站

專項

zhuan1xiang4

ATTR。專用

我只知道一點Java。如何將第一種格式轉換爲第二種格式?

+7

Stackoverflow是一個編程問題的答案的地方。這不是學習編程基礎的地方。 – jomsk1e

+0

只是谷歌它:從文件讀取Java,寫文件等 – Tala

+0

另外我不會選擇Java來完成這項任務。 Perl(或任何其他腳本語言)更適合於此。 – m0skit0

回答

0

即使它看起來像一個練習。但理想情況下,你可以做。

  • 獲取該文件的內容(使用commons-IO)
  • 新線替換選項卡並寫入文件

示例代碼

import java.io.File; 
    import java.io.IOException; 

    import org.apache.commons.io.FileUtils; 

    public class Test { 

     /** 
     * @param args 
     * @throws IOException 
     */ 
     public static void main(String[] args) throws IOException { 
      String path = "C:/test.txt"; 
      // TODO Auto-generated method stub 
      File file = new File(path); 

      String string = FileUtils.readFileToString(file); 
      String finalString = string.replaceAll("\t", "\n"); 
      FileUtils.write(file, finalString); 

     } 

} 

現在的文件看起來像

淫穢 
yin2hui4 
obscene; salacious; bawdy 

    網站 
wang3zhan4 
website 

    專項 
zhuan1xiang4 
attr. earmarked 
+0

如果文件的大小是幾GB呢?你真的想把整個文件加載到一個'String'中嗎? – zEro

+0

他沒有提到過。 – Makky

+0

我不是OP,但我只是建議你可以編輯你的答案來提供限制。歡呼:) – zEro

2

顯然,我們d不想做你的功課。但我們不想讓你們擱淺。

我已經打開了許多東西,下面只是一個Java看起來的僞代碼。你可以從這裏開始...

FileReader reader = ... // open the file reader using the input file 
FileWriter writer = ...// open a file for writing output 

while(the stream doesn't end) { // provide the condition, as must be 
    String line = ... // read a line from the reader 
    String character = line.substring(0, line.indexOf("\t")), 
      pronounciation = line.substring(character.length() -1).substring(line.indexOf("\t", character.length()), 
      definition = line.substring(line.lastIndexOf("\t")); // Obviously, this isn't accurate.... you need to work around this. 

    writeLineToFile(character) 
    writeLineToFile(pronounciation) 
    writeLineToFile(definition) 

} 

close the reader and writer 
相關問題