2017-11-11 70 views
-1

所以我做到了這一點,到目前爲止,我的程序工作,例如轉向數字123 ...到像abc信...Java的字母替換文件

但我的問題是我不能使它與專項工作字符如:č, ć, đ。問題是當我運行它與特殊字符我的文件只是得到刪除

編輯:忘了提IM與.srt文件時,將UTF-8在掃描儀工作了txt文件,但是當我用.srt tryed它只是從文件中刪除完整contect。

代碼:

LinkedList<String> lines = new LinkedList<String>(); 

// Opening the file 
Scanner input = new Scanner(new File("input.srt"), "UTF-8"); 
while (input.hasNextLine()) { 
    String line = input.nextLine(); 
    lines.add(replaceLetters(line)); 
} 
input.close(); 

// Saving the new edited version file 
PrintWriter writer = new PrintWriter("input.srt", "UTF-8"); 
for (String line: lines) { 
    writer.println(line); 
} 
writer.close(); 

替換法:

public static String replaceLetters(String orig) { 
    String fixed = ""; 
    // Go through each letter and replace with new letter 
    for (int i = 0; i < orig.length(); i++) { 
     // Get the letter 
     String chr = orig.substring(i, i + 1); 
     // Replace letter if nessesary 
     if (chr.equals("a")) { 
      chr = "1"; 
     } else if (chr.equals("b")) { 
      chr = "2"; 
     } else if (chr.equals("c")) { 
      chr = "3"; 
     } 

     // Add the new letter to the end of fixed 
     fixed += chr; 
    } 
    return fixed; 
} 
+0

請詳細解釋您要實現的目標。還舉一些例子。 – Zabuza

+0

請注意,如今您應該使用Javas新的I/O庫(名爲** NIO **)來讀取和寫入文件。它圍繞'Paths','Files'和'Path'旋轉。 – Zabuza

回答

1

把你

Scanner input = new Scanner(new File("input.txt")); 

Scanner input = new Scanner(new File("input.txt"), "UTF-8"); 

您可以保存在UTF-8中,但可以讀入默認字符集。

另外,下次正確使用try-catch聲明並將它們包含在您的文章中。

+0

擴展答案:使用** NIO **,您不再有這樣的問題。如果沒有指定其他內容,它總是默認使用** UTF-8 **。例如'Files.write(...)'和'Files.lines(...)'。 – Zabuza