2017-11-11 152 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