#1
2nd April 2023, 05:07 PM
|
|||
|
|||
Copy contents from a file to string
A file is having some data. We can transfer that data to another file using some streams LikeDataInputStream,OutputStreams
While doing this I would like to store that data in a string array and then do the transefer. |
#2
4th April 2023, 01:57 AM
|
|||
|
|||
Re: Copy contents from a file to string
You can easily read the contents of a file into a string using the FileReader and BufferedReader classes in Java. Here's an example code snippet that demonstrates how to do it:
Code:
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class FileToStringExample { public static void main(String[] args) { try { BufferedReader reader = new BufferedReader(new FileReader("input.txt")); StringBuilder stringBuilder = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { stringBuilder.append(line); stringBuilder.append(System.lineSeparator()); } reader.close(); String fileContents = stringBuilder.toString(); System.out.println(fileContents); } catch (IOException e) { e.printStackTrace(); } } } Note that we use the System.lineSeparator() method to add the line separator character to the string after each line. This is necessary because the readLine() method of the BufferedReader class does not include the line separator character in the returned string. ~Best Regards Suraj Pratap Singh M.Tech (CSE, final) |
|
Related Topics: |
||
Thread | Replies | Last Post |
The client passes requests for file records over a network to the file server is a case of? | 0 | 24th November 2022 08:13 PM |
|