In Java, how would I convert an entire input file into one String?
In other words, if I have an input file "test.in":
c++
java
python
test
then I want to create a String containing "c++javapythontest".
I thought of something along the lines of
Scanner input = new Scanner(new File("test.in"));
while(input.hasNext()){
String test = test + input.nextLine();
}
but that doesn't seem to work.
Is there an efficient way to do this?
To read file contents, discarding newline chars:
String contents = Files.lines(Paths.get("test.in")).collect(Collectors.joining());
I think you needed to test for hasNextLine(), and your code's performance suffers from the creation of so many objects when you concatenate strings like that. If you changed your code to use a StringBuilder, it would run much faster.
There could be many ways to do it. One of the ways you can try is using the nio package classes. You can use the readAllBytes method of the java.nio.file.Files class to get a byte array first and then create a new String object from the byte array new String(bytes).
Read the Java Doc of this method.
Following is a sample program:
byte[] bytes= Files.readAllBytes(Paths.get(filePath));
String fileContent = new String(bytes);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With