gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
How do I read a text file into a string from an input stream as a one liner in Java?
- User
How do I read a text file into a string from an input stream as a one liner in Java?
- Assistant
In Java, you can read a text file into a string from an input stream in a one-liner using the
Scannerclass and theuseDelimiter()method. Here's an example:javaimport java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Main { public static void main(String[] args) { try { String fileContent = new Scanner(new File("file.txt")).useDelimiter("\\Z").next(); System.out.println(fileContent); } catch (FileNotFoundException e) { e.printStackTrace(); } } }This code performs the following steps:
- Creates a new
Scannerobject, passing the file name or path to theFileconstructor. - Uses the
useDelimiter()method to set the delimiter to the end of the file (\\Z). This ensures that the whole file is read as a single string.
- Creates a new