简体   繁体   中英

Can't write text into file

I want to write int into text file. 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. Any ideas to do it?

You should be using PrintWriter.print(int)

Writer.write() outputs one character, that's what it's for. Don't get confused by int parameter type. Wrap your osw in PrintWriter, don't forget to close that.

 osw.write(i);

This line writes the character to the file whose unicode value is i

You should use PrintWriter to write your integer value.

OutputStreamWriter is a stream to print characters.

Try using a PrintWriter like this:

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. Have a look at the Ascii table for a reference of what int represents which char .

If you really wanted you write the number with characters , consider using a PrintWriter instead of a OutputStreamWriter . You could also change your int into a String ( Integer.toString(i) ) and still use your OutputStreamWriter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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