#1  
2nd April 2023, 04:07 PM
Unregistered
Guest
 
Posts: n/a

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, 12:57 AM
SurajPSingh
Junior Member
 
Join Date: Feb 2023
Posts: 318
Default 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();
        }
    }
}
In this example, we first create a BufferedReader object and wrap it around a FileReader object that reads the contents of the file "input.txt". We then use a StringBuilder object to accumulate the contents of the file into a single string. Finally, we close the BufferedReader object and print the file contents to the console.

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)
Do you have any question? or have anything to say?



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 07:13 PM



Powered by vBulletin® Version 3.8.3
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.3.0
vBulletin Optimisation by vB Optimise.
Please also check: