Writer write int java

Java Writer

The Java Writer class ( java.io.Writer ) is the base class for all Writer subclasses in the Java IO API. A Writer is like an OutputStream except that it is character based rather than byte based. In other words, a Writer is intended for writing text, whereas an OutputStream is intended for writing raw bytes.

Characters in Unicode

Today, many applications use Unicode (typically UTF-8 or UTF-16) to store text data. It may take one or more bytes to represent a single character in UTF-8. In UTF-16 each character takes 2 bytes to represent. To write UTF-8 or UTF-16 correctly you need to know which of the two formats you want to store the text in, and you need to know how to properly encode characters using the chosen format.

This is where the Java Writer class comes in handy. The Java Writer subclasses can normally handle UTF-8 and UTF-16 encoding for you, so you don’t have to worry about that.

Writer Subclasses

You will normally use a Writer subclass rather than a Writer directly. Subclasses of Writer include OutputStreamWriter , CharArrayWriter , FileWriter , plus many others. Here is a list of the Java Writer subclasses:

Writers and Destinations

A Java Writer is typically connected to some destination of data like a file, char array, network socket etc. This is also explained in more detail in the Java IO Overview text.

Читайте также:  Html utf character encoding

write(int)

The Java Writer write(int) method writes the lower 16 bit of the int to the destination the Writer is connected to, as a single character. Here is an example of writing a single character to a Java Writer :

Writer writer = new FileWriter("data/output.txt"); writer.write('A');

write(char[])

The Java Writer also has a write(char[]) method which can write an array of characters to the destination the Writer is connected to. The write(char[]) method returns the number of characters actually written to the Writer . Here is an example of writing an array of chars to a Java Writer :

Writer writer = new FileWriter("data/output.txt"); char[] chars = new char[]; writer.write(chars);

Write Performance

It is faster to write an array of characters to a Java Writer than writing one character at a time. The speedup can be quite significant — up to 10 x higher or more. Therefore it is recommended to use the write(char[]) methods whenever possible.

The exact speedup you get depends on the underlying OS and hardware of the computer you run the Java code on. The speedup depends on issues like memory speed, hard disk speed and buffer sizes, or network card speed and buffer sizes, depending on which destination the Writer sends its data to.

Transparent Buffering via BufferedWriter

You can get transparent buffering of bytes written to a Java Writer by wrapping it in a Java BufferedWriter . All bytes written to the BufferedWriter will first get buffered inside an internal byte array in the BufferedWriter . When the buffer is full, the buffer is flushed to the underlying Writer all at once. Here is an example of wrapping a Java Writer in a BufferedWriter :

int bufferSize = 8 * 1024; Writer writer = new BufferedWriter( new FileWriter("c:\\data\\output-file.txt"), bufferSize );

You can read more about the BufferedWriter in my BufferedWriter tutorial.

flush()

The Java Writer ‘s flush() method flushes all data written to the Writer to the underlying data destination. For instance, if the Writer is a FileWriter then bytes written to the FileWriter may not have been fully written to disk yet. The data might be buffered in OS memory somewhere, even if your Java code has written it to the FileWriter . By calling flush() you can assure that any buffered data will be flushed (written) to disk (or network, or whatever else the destination of your Writer has). Here is an example of flushing data written to a Java Writer by calling its flush() method:

Close a Writer

Once you are done writing characters to a Java Writer you should close it. You close an Writer by calling its close() method. Here is an example of closing a Java Writer :

Writer writer = new FileWriter("c:\\data\\output-text.txt"); while(hasMoreCharacters()) < int character = getNextCharacter(); writer.write(character); >writer.close();

The concrete implementations of hasMoreCharacters() and getNextCharacter() are left out, but they are not really super important to understand the principle of this example. What matters is, that once the while loop ends, and you are done writing data to the Writer , its close() method is called, which closes the Writer .

The above example is not fully robust though. In case the write() method throws an exception, the close() method will never get called. The exception will make the program exit whatever method the above code is located in.

Instead, you should use the Java try with resources construct to close the Writer . Here is an example that closes a Java Writer using the try-with-resources construct:

try( Writer writer = new FileWriter("c:\\data\\output-text.txt")) < while(hasMoreCharacters()) < int character = getNextCharacter(); writer.write(character); >>

Once the try block is exited, the close() method of the Writer is called automatically, because the Writer was declared inside the parentheses of the try block. Even if an exception is thrown from inside the try block, the close() method is still called before the exception is propagated up the call stack.

Источник

Class Writer

Abstract class for writing to character streams. The only methods that a subclass must implement are write(char[], int, int), flush(), and close(). Most subclasses, however, will override some of the methods defined here in order to provide higher efficiency, additional functionality, or both.

Field Summary

Constructor Summary

Method Summary

Methods declared in class java.lang.Object

Field Details

lock

The object used to synchronize operations on this stream. For efficiency, a character-stream object may use an object other than itself to protect critical sections. A subclass should therefore use the object in this field rather than this or a synchronized method.

Constructor Details

Writer

Writer

Method Details

nullWriter

Returns a new Writer which discards all characters. The returned stream is initially open. The stream is closed by calling the close() method. Subsequent calls to close() have no effect. While the stream is open, the append(char) , append(CharSequence) , append(CharSequence, int, int) , flush() , write(int) , write(char[]) , and write(char[], int, int) methods do nothing. After the stream has been closed, these methods all throw IOException . The object used to synchronize operations on the returned Writer is not specified.

write

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. Subclasses that intend to support efficient single-character output should override this method.

write

write

write

write

append

Appends the specified character sequence to this writer. An invocation of this method of the form out.append(csq) behaves in exactly the same way as the invocation

Depending on the specification of toString for the character sequence csq , the entire sequence may not be appended. For instance, invoking the toString method of a character buffer will return a subsequence whose content depends upon the buffer’s position and limit.

append

Appends a subsequence of the specified character sequence to this writer. Appendable . An invocation of this method of the form out.append(csq, start, end) when csq is not null behaves in exactly the same way as the invocation

 out.write(csq.subSequence(start, end).toString()) 

append

Appends the specified character to this writer. An invocation of this method of the form out.append(c) behaves in exactly the same way as the invocation

flush

Flushes the stream. If the stream has saved any characters from the various write() methods in a buffer, write them immediately to their intended destination. Then, if that destination is another character or byte stream, flush it. Thus one flush() invocation will flush all the buffers in a chain of Writers and OutputStreams. If the intended destination of this stream is an abstraction provided by the underlying operating system, for example a file, then flushing the stream guarantees only that bytes previously written to the stream are passed to the operating system for writing; it does not guarantee that they are actually written to a physical device such as a disk drive.

close

Closes the stream, flushing it first. Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown. Closing a previously closed stream has no effect.

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Источник

Оцените статью