Java program to create string from contents of a file
Sure, here's a Java program that creates a string from the contents of a file:
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class FileToString { public static void main(String[] args) { String fileName = "file.txt"; String fileContents = ""; try (BufferedReader br = new BufferedReader(new FileReader(fileName))) { String line; while ((line = br.readLine()) != null) { fileContents += line + "\n"; } } catch (IOException e) { e.printStackTrace(); } System.out.println(fileContents); } }
In this program, we first specify the name of the file we want to read using the fileName
variable.
We then create an empty string called fileContents
.
We use a try-with-resources block to create a BufferedReader
object that reads the file. We then read the file line by line using the readLine
method of the BufferedReader
object. If the line is not null
, we append it to the fileContents
string along with a newline character.
Finally, we print out the fileContents
string to confirm that the file contents were successfully read into the string.
Note that this program assumes that the file is located in the same directory as the program. If the file is located in a different directory, you will need to specify the full path to the file in the fileName
variable.