There are various ways to read a Text file.
- BufferedReader
- Files
- commons-io의 FileUtil
Let`s see how to read a text file through an example.
Read text file using BufferedReader
You can read text files using BufferedReader. Just pass the FileReader object as an argument to the constructor of BufferedReader.
You can read the text.txt
file and output the text like this:
File file = new File("/home/js/test/text.txt");
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
readLine()
returns null if there is no more to read.
Running it, the result is:
Chicago – April 28, 2020 Society for Incentive Travel Excellence (SITE) will hold its third Covid-19 related webinar Friday, May 1, at 10AM (Chicago) 4PM (London) 11PM (Singapore).
With previous webinars having attracted a cumulative audience of over 700 incentive travel professionals, we now turn our attention to Health Security in a Post Covid-19 World.
Reading text files using Files
You can read and print text files using Files.
The following code outputs the contents of text.txt.
readAllLines()
returns a list of strings of files.
try {
Path path = Paths.get("/home/js/test/text.txt");
List<String> lines = Files.readAllLines(path);
for(String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
If you want to use Files and BufferedReader, you can also implement it like this:
Path path = Paths.get("/home/js/test/text.txt");
try (BufferedReader reader = Files.newBufferedReader(path)) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
(newBufferedReader()
seems to be available since Java8.)
result
Chicago – April 28, 2020 Society for Incentive Travel Excellence (SITE) will hold its third Covid-19 related webinar Friday, May 1, at 10AM (Chicago) 4PM (London) 11PM (Singapore).
With previous webinars having attracted a cumulative audience of over 700 incentive travel professionals, we now turn our attention to Health Security in a Post Covid-19 World.
Read text file using commons-io library
You can also read files using the commons-io library.
Gradle project adds the following to dependencies of build.gradle
.
dependencies {
compile group: 'commons-io', name: 'commons-io', version: '2.6'
...
}
For projects that use other build systems such as Maven, refer to mvnrepository.com and configure it.
The following is the code to read a file using FileUtils of commons-io. readLines()
takes an encoding type as an argument. And it returns a list of strings.
try {
File file = new File("/home/js/test/text.txt");
List<String> lines = FileUtils.readLines(file, "UTF-8");
for(String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
If Listt need to receive it as , and you can return a String object with all the texts combined, you can use
readFileToString()`.
System.out.println();
try {
File file = new File("/home/js/test/text.txt");
String strings = FileUtils.readFileToString(file, "UTF-8");
System.out.println(strings);
} catch (IOException e) {
e.printStackTrace();
}
The execution result is the same as the above codes. just concatenated into one string. (concatenated)
result
Chicago – April 28, 2020 Society for Incentive Travel Excellence (SITE) will hold its third Covid-19 related webinar Friday, May 1, at 10AM (Chicago) 4PM (London) 11PM (Singapore).
With previous webinars having attracted a cumulative audience of over 700 incentive travel professionals, we now turn our attention to Health Security in a Post Covid-19 World.
Reference
Related Posts
- Java - Remove items from List while iterating
- Java - How to find key by value in HashMap
- Java - Update the value of a key in HashMap
- Java - How to put quotes in a string
- Java - How to put a comma (,) after every 3 digits
- BiConsumer example in Java 8
- Java 8 - Consumer example
- Java 8 - BinaryOperator example
- Java 8 - BiPredicate Example
- Java 8 - Predicate example
- Java 8 - Convert Stream to List
- Java 8 - BiFunction example
- Java 8 - Function example
- Java - Convert List to Map
- Exception testing in JUnit
- Hamcrest Collections Matcher
- Hamcrest equalTo () Matcher
- AAA pattern of unit test (Arrange/Act/Assert)
- Hamcrest Text Matcher
- Hamcrest Custom Matcher
- Why Junit uses Hamcrest
- Java - ForkJoinPool
- Java - How to use Futures
- Java - Simple HashTable implementation
- Java - Create a file in a specific path
- Java - Mockito의 @Mock, @Spy, @Captor, @InjectMocks
- Java - How to write test code using Mockito
- Java - Synchronized block
- Java - How to decompile a ".class" file into a Java file (jd-cli decompiler)
- Java - How to generate a random number
- Java - Calculate powers, Math.pow()
- Java - Calculate the square root, Math.sqrt()
- Java - How to compare String (==, equals, compare)
- Java - Calculate String Length
- Java - case conversion & comparison insensitive (toUpperCase, toLowerCase, equalsIgnoreCase)