Java BufferedReader transferTo() Method
Example
Copy all text from a file to a StringWriter, and print it:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
public class Main {
public static void main(String[] args) throws IOException {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("Volvo\nBMW\nFord");
myWriter.close();
BufferedReader br = new BufferedReader(new FileReader("filename.txt"));
StringWriter sw = new StringWriter();
br.transferTo(sw);
br.close();
System.out.println(sw);
}
}
Definition and Usage
The transferTo() method reads all the remaining characters from the reader, and writes them to the writer that you give it. It returns the number of characters that were transferred.
In the example, the writer is a StringWriter (a writer that collects the text in memory, as a String).
Syntax
public long transferTo(Writer out)
Parameter Values
| Parameter | Description |
|---|---|
| out | Required. The writer to write the characters to. |
Technical Details
| Returns: | The number of characters that were transferred, as a long. |
|---|---|
| Java version: | Java 10 |
Related Pages
❮ BufferedReader Methods