开发者

Write int to text file using Writer

开发者 https://www.devze.com 2023-04-03 13:10 出处:网络
Writer wr = new FileWriter(\"123.txt\"); wr.write(123); wr.close(); Output file contains: { Where is the problem开发者_开发百科? How to write int to text file using Writer?You have to write String
Writer wr = new FileWriter("123.txt");
wr.write(123);
wr.close();

Output file contains:

{

Where is the problem开发者_开发百科? How to write int to text file using Writer?


You have to write String...

you can try.

wr.write("123");

OR

wr.write(new Integer(123).toString());

OR

wr.write( String.valueOf(123) );


There is also a very simple way to write integers to file using FileWriter:

Writer wr = new FileWriter("123.txt");
wr.write(123 + "");
wr.close();

The + "" concatenates the integers with an empty string, thus parsing the integer to string. Very easy to do and to remember.


Javadocs are your friend:

Convenience class for writing character files.

} is the character with the ASCII value 123.

If you want to write the text representation of 123 to this file, you'd want to do:

wr.write(Integer.toString(123));


123 = 0x7b = ascii code for {, so you are writing the character to the file. Use the toString() method to convert the value to a string and output it.


I have had a good experience in the past with PrintStream. PrintStream can be used in two ways (at least)

PrintStream ps = new PrintStream("file_location.txt");

OR

PrintStream ps = new PrintStream(new File("file_loc.txt"));

and to write, use:

ps.println("String text");

OR

ps.println(Integer.parseInt(123));


The problem is that Writer.write is used to send a single character to the output. It's not clear why it's int rather than char, admittedly - it would make sense if you could use this to send non-BMP characters, but the documentation states:

Writes a single character. The character to be written is contained in the 16 low-order bits of the given integer value; the 16 high-order bits are ignored.

You need to convert your integer to a string first, e.g.

int v = 123; // I'm assuming this is dynamic in reality
wr.write(String.valueOf(v));


Yet one method:

wr.write(""+123); //immediately convert int to its String representation

or

wr.write(""+i);

But I don't know, how it affect in perfomance versus other methods, but it is a little simpler to write. :)

PS: Sorry for my may be bad English


This is what you are trying. See this.

http://download.oracle.com/javase/1.4.2/docs/api/java/io/Writer.html#write(int)

This is the method name in the javadoc im reffering to, incase if the link doesn't take you automatically.

public void write(int c)
       throws IOException

So, the equivalent ascii character for 123 is {

Thanks

0

精彩评论

暂无评论...
验证码 换一张
取 消