Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert an entire input file into a string? [duplicate]

Tags:

java

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?

like image 319
borndeft Avatar asked Oct 26 '25 04:10

borndeft


2 Answers

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.

like image 174
Bohemian Avatar answered Oct 28 '25 16:10

Bohemian


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);
like image 24
VHS Avatar answered Oct 28 '25 16:10

VHS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!