1

我正在编写一个小程序,它只需要一个文件,并在空格后修剪最后 4 个字符并将它们写入一个新文件。当我告诉它这样做然后将它们打印到控制台时,它工作正常。他们表现得很好,一切正常。但是当我使用 BufferedWriter 将它写入一个新文件时,当我检查它时,它会在该文件中给我一个奇怪的字符串。这是我的代码:

package trimmer;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class trimmer {

private File file;
private File newfile;

private Scanner in;

public void Create() {

    String temp, temp1;

    try {

        setScanner(new Scanner(file));
    } catch (FileNotFoundException e) {
        System.out.println("file not found!!");

    }

    if (!newfile.exists()) {
        try {
            newfile.createNewFile();
            FileWriter fw = new FileWriter(newfile.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            while (in.hasNextLine()) {
                temp1 = in.nextLine();
                temp = temp1.substring(temp1.lastIndexOf(' ') + 1);
                System.out.println(temp);
                bw.write(temp);
            }
            bw.close();
            System.out.println("done!");

        } catch (IOException e) {
            System.out.println("Could not make new file: " + newfile + " Error code: " + e.getMessage());
        }
    }

}

public Scanner getScanner() {
    return in;
}

public void setScanner(Scanner in) {
    this.in = in;
}

public File getFile() {
    return file;
}

public void setFile(File file) {
    this.file = file;
}

public File getNewfile() {
    return newfile;
}

public void setNewfile(File newfile) {
    this.newfile = newfile;
}

}

当我检查文件时,它看起来像这样:

䐳噔吳商吳啍唳噎吳剄唳剄䘳剄唳噎吳商䠳卉䌳䕎䜳䱁䠳卉䴳㉕倳乓䐳䍐䐳啐吳䍖吳乓吳啍䔳䥘䌳噔匳剕唳乓唳䅍䌳䕎䜳䱁䴳㉕倳乓䐳䍐䐳啐吳䍖䠳卉吳乓吳啍䔳䥘䌳噔匳剕唳乓唳䅍

谁能告诉我为什么会这样?

4

1 回答 1

2

FileWriter 使用平台默认字符编码。If this is not the encoding that you want, then you need to use an OutputStreamWriter with the appropriately chosen character encoding.

于 2013-03-28T03:26:30.223 回答