4

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?

Bohemian
  • 412,405
  • 93
  • 575
  • 722
borndeft
  • 75
  • 7

6 Answers6

5

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.

Saravana
  • 12,647
  • 2
  • 39
  • 57
Bohemian
  • 412,405
  • 93
  • 575
  • 722
1

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);
VHS
  • 9,534
  • 3
  • 19
  • 43
0

Declare the String test out of the loop, then iterate filling it.

0

This code is a small modification to your original logic.
StringBuilder creates a mutable sequence of characters which means we just append the content to the value of StringBuilder object instead of creating a new object everytime.

In your code String test = test + input.nextLine(); was inside while loop.
Thus fresh objects of String test were created with every iteration of while loop and therefore it was not saving previous values.

String path = "test.txt";
Scanner input = new Scanner(new File(path));
StringBuilder sb = new StringBuilder();

while (input.hasNext()) {
    sb.append(input.nextLine() + "\n");
}
System.out.println(sb.toString());
Devendra Lattu
  • 2,732
  • 2
  • 18
  • 27
0

You can try this instead.
Its a simple one liner

String str = new String(Files.readAllBytes(Paths.get("/path/to/file")));

This reads the entire file and keeps it as String.
If you want to remove new line characters.

str.replace("\n", "");

skap
  • 493
  • 4
  • 9
0

String.join has been added in Java8 which internally uses StringBuilder

String content = String.join("", Files.readAllLines(Paths.get("test.in")));
Saravana
  • 12,647
  • 2
  • 39
  • 57