Does Java has a one line instruction to read to a text file, like what C# has?
I mean, is there something equivalent to this in Java?:
String data =
Java 11 adds support for this use-case with Files.readString, sample code:
Files.readString(Path.of("/your/directory/path/file.txt"));
Before Java 11, typical approach with standard libraries would be something like this:
public static String readStream(InputStream is) {
StringBuilder sb = new StringBuilder(512);
try {
Reader r = new InputStreamReader(is, "UTF-8");
int c = 0;
while ((c = r.read()) != -1) {
sb.append((char) c);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return sb.toString();
}
Notes:
With JDK/11, you can read a complete file at a Path as a string using Files.readString(Path path):
try {
String fileContent = Files.readString(Path.of("/foo/bar/gus"));
} catch (IOException e) {
// handle exception in i/o
}
the method documentation from the JDK reads as follows:
/**
* Reads all content from a file into a string, decoding from bytes to characters
* using the {@link StandardCharsets#UTF_8 UTF-8} {@link Charset charset}.
* The method ensures that the file is closed when all content have been read
* or an I/O error, or other runtime exception, is thrown.
*
* <p> This method is equivalent to:
* {@code readString(path, StandardCharsets.UTF_8) }
*
* @param path the path to the file
*
* @return a String containing the content read from the file
*
* @throws IOException
* if an I/O error occurs reading from the file or a malformed or
* unmappable byte sequence is read
* @throws OutOfMemoryError
* if the file is extremely large, for example larger than {@code 2GB}
* @throws SecurityException
* In the case of the default provider, and a security manager is
* installed, the {@link SecurityManager#checkRead(String) checkRead}
* method is invoked to check read access to the file.
*
* @since 11
*/
public static String readString(Path path) throws IOException
Here are 3 ways to read a text file in one line, without requiring a loop. I documented 15 ways to read from a file in Java and these are from that article.
Note that you still have to loop through the list that's returned, even though the actual call to read the contents of the file requires just 1 line, without looping.
1) java.nio.file.Files.readAllLines() - Default Encoding
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;
public class ReadFile_Files_ReadAllLines {
public static void main(String [] pArgs) throws IOException {
String fileName = "c:\\temp\\sample-10KB.txt";
File file = new File(fileName);
List fileLinesList = Files.readAllLines(file.toPath());
for(String line : fileLinesList) {
System.out.println(line);
}
}
}
2) java.nio.file.Files.readAllLines() - Explicit Encoding
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
public class ReadFile_Files_ReadAllLines_Encoding {
public static void main(String [] pArgs) throws IOException {
String fileName = "c:\\temp\\sample-10KB.txt";
File file = new File(fileName);
//use UTF-8 encoding
List fileLinesList = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
for(String line : fileLinesList) {
System.out.println(line);
}
}
}
3) java.nio.file.Files.readAllBytes()
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
public class ReadFile_Files_ReadAllBytes {
public static void main(String [] pArgs) throws IOException {
String fileName = "c:\\temp\\sample-10KB.txt";
File file = new File(fileName);
byte [] fileBytes = Files.readAllBytes(file.toPath());
char singleChar;
for(byte b : fileBytes) {
singleChar = (char) b;
System.out.print(singleChar);
}
}
}
Java 7 improves on this sorry state of affairs with the Files class (not to be confused with Guava's class of the same name), you can get all lines from a file - without external libraries - with:
List<String> fileLines = Files.readAllLines(path, StandardCharsets.UTF_8);
Or into one String:
String contents = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
// or equivalently:
StandardCharsets.UTF_8.decode(ByteBuffer.wrap(Files.readAllBytes(path)));
If you need something out of the box with a clean JDK this works great. That said, why are you writing Java without Guava?