Java Can';不要将文本写入文件

Java Can';不要将文本写入文件,java,Java,我想把int写入文本文件。 我写了这段代码 public static void WriteInt(int i,String fileName){ File directory = new File("C:\\this\\"); if (!directory.exists()) { directory.mkdirs(); } File file = new File("C\\"+fileName); FileOutputStream fOu

我想把int写入文本文件。 我写了这段代码

public static void WriteInt(int i,String fileName){
    File directory = new File("C:\\this\\");
    if (!directory.exists()) {
        directory.mkdirs();
    }
    File file = new File("C\\"+fileName);
    FileOutputStream fOut = null;

    try {
        //Create the stream pointing at the file location
        fOut = new FileOutputStream(new File(directory, fileName));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    OutputStreamWriter osw = new OutputStreamWriter(fOut);
    try {

        osw.write(i);


        osw.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
但在输出文件中,我没有int,只有一个符号。
有什么想法吗?

您应该使用PrintWriter.print(int)


Writer.write()输出一个字符,这就是它的用途。不要被int参数类型搞糊涂了。将osw包装在PrintWriter中,不要忘记关闭它。

您应该使用PrintWriter.print(int)

 osw.write(i);
Writer.write()输出一个字符,这就是它的用途。不要被int参数类型搞糊涂了。用PrintWriter包装您的osw,别忘了关闭它

 osw.write(i);
此行将字符写入unicode值为
i

您应该使用
PrintWriter
来写入整数值

此行将字符写入unicode值为
i


您应该使用
PrintWriter
写入整数值。

OutputStreamWriter
是用于打印字符的流

尝试使用类似以下的方法:

try(FileWriter fw = new FileWriter(file); 
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter pw = new PrintWriter(bw)) {
    pw.print(i);
}

OutputStreamWriter
是用于打印字符的流

尝试使用类似以下的方法:

try(FileWriter fw = new FileWriter(file); 
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter pw = new PrintWriter(bw)) {
    pw.print(i);
}

我猜您的问题是,您希望在文件中以人类可读的格式找到数字,但您正在使用的OutputStreamWriter方法(接收int)希望接收字符表示。请查看,以获取int代表char的引用


如果你真的想用<强>字符< /强>来写数字,请考虑使用<强> PrimTrrter < /Stand >而不是<强> OutUpDeFraseWrase/Stult>。您还可以将int更改为字符串(Integer.toString(i)),并且仍然使用OutputStreamWriter

我想您的问题是,您希望在文件中以人类可读的格式找到数字,但是您使用的OutputStreamWriter方法(接收int)希望接收char表示。请查看,以获取int表示哪个char的参考


如果你真的想用<强>字符写数字,考虑使用<强> PrimTrrter < /String >而不是<强> OuttoStrutsReals> /String >。还可以将<强> int /String >更改为字符串(<强>整数。toString(i)< /强>)并且仍然使用你的输出流编写器

@Leo-很可能是一个打字错误改成了C:\\但仍然不起作用。@Leo-很可能是一个打字错误改成了C:\\但仍然不起作用。是的!这是我需要的。谢谢。是的!这是我需要的。谢谢。