文件

时间:2017-11-11 19:20:31

标签: java file

所以我到目前为止这样做了,我的程序就是将数字123 ...转换为abc等字母......

但我的问题是我无法使用像č, ć, đ这样的特殊字符。问题是,当我使用特殊字符运行时,我的文件只是被删除

修改:忘了提及我使用.srt文件,在扫描仪中添加utf-8用于txt文件,但当我尝试使用.srt时,它只是删除了来自档案。

代码:

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;
}

1 个答案:

答案 0 :(得分:1)

转动你的

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

进入

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

您保存在UTF-8,但是在默认字符集中读取。

另外,下次正确使用try-catch语句并将其包含在帖子中。