Write a Reader to File in Java
In this tutorial, we will see how to write the contents of a Reader to a File using different ways.1). Using core Java.
In core java, we have Reader and writer classes. First, we create a reader object in which we hold the String content, then we iterate the reader for each character and write the content to the file using the writer object.
try {
Reader reader = new StringReader("Hello World!!!!");
int intValueOfChar;
StringBuilder sb = new StringBuilder();
while ((intValueOfChar = reader.read()) != -1) {
sb.append((char) intValueOfChar);
}
reader.close();
File targetFile = new File("src/main/resources/file.txt");
targetFile.createNewFile();
Writer fileWriter = new FileWriter(targetFile);
fileWriter.write(sb.toString());
fileWriter.close();
} catch(IOException ex) {
System.out.println(ex.getMessage());
}
2). Using Apache common IO
The apache common IO contains the classes like FileUtils and IOUtils, in which we can read data from the Reader and write that data to file.
Maven dependencies
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.8.0</version>
</dependency>
try {
Reader reader = new CharSequenceReader("Hello World!!!!");
File targetFile = new File("src/main/resources/targetFile.txt");
FileUtils.touch(targetFile);
byte[] buffer = IOUtils.toByteArray(reader);
FileUtils.writeByteArrayToFile(targetFile, buffer);
reader.close();
} catch(IOException ex) {
System.out.println(ex.getMessage());
}
3). Using Google Guava
Similar to Apache common IO, Guava has the Files class contains the utility methods to Write a Reader to File.
Maven dependencies
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>30.0-jre</version>
</dependency>
try {
Reader reader = new StringReader("Hello World!!!");
File targetFile = new File("src/main/resources/targetFile.txt");
com.google.common.io.Files.touch(targetFile);
CharSink charSink = com.google.common.io.Files.
asCharSink(targetFile, Charset.defaultCharset(), FileWriteMode.APPEND);
charSink.writeFrom(initialReader);
reader.close();
} catch(IOException ex) {
System.out.println(ex.getMessage());
}
In this article, we have seen Write a Reader to File in Java.
0 Comments
Post a Comment