简体   繁体   English

无法将文字写入档案

[英]Can't write text into file

I want to write int into text file. 我想将int写入文本文件。 I wrote this code 我写了这段代码

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

But in output file I have no int , just one symbol. 但是在输出文件中,我没有int,只有一个符号。 Any ideas to do it? 有什么想法吗?

You should be using PrintWriter.print(int) 您应该使用PrintWriter.print(int)

Writer.write() outputs one character, that's what it's for. Writer.write()输出一个字符,这就是它的作用。 Don't get confused by int parameter type. 不要对int参数类型感到困惑。 Wrap your osw in PrintWriter, don't forget to close that. 将您的OSW包装在PrintWriter中,别忘了关闭它。

 osw.write(i);

This line writes the character to the file whose unicode value is i 该行将字符写入unicode值为i的文件中

You should use PrintWriter to write your integer value. 您应该使用PrintWriter写入整数值。

OutputStreamWriter is a stream to print characters. OutputStreamWriter是用于打印字符的流。

Try using a PrintWriter like this: 尝试像这样使用PrintWriter

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

I guess your problem is that you expected to literally find the number in human-readable format in your file, but the method of the OutputStreamWriter you're using (which receives a int ) expect to receive a char representation. 我猜您的问题是您希望在文件中从字面上查找人类可读格式的数字,但是您正在使用的OutputStreamWriter的方法(接收一个int )期望接收一个char表示形式。 Have a look at the Ascii table for a reference of what int represents which char . 查看Ascii表以获取int代表哪个char的引用。

If you really wanted you write the number with characters , consider using a PrintWriter instead of a OutputStreamWriter . 如果您真的想用字符写数字,请考虑使用PrintWriter而不是OutputStreamWriter You could also change your int into a String ( Integer.toString(i) ) and still use your OutputStreamWriter 您也可以将int更改为String( Integer.toString(i) )并仍然使用OutputStreamWriter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM