How to read file in Java

This commit is contained in:
Umesh Awasthi
2020-01-19 20:03:54 -08:00
parent 558d38437d
commit eff001491e
10 changed files with 269 additions and 0 deletions

2
Java/java-read-file/.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,2 @@
# Default ignored files
/workspace.xml

View File

@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4" />

View File

@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.javadevjournal</groupId>
<artifactId>java-read-file</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,29 @@
package com.javadevjournal.read.file;
import java.io.IOException;
public class JavaReadFileTest {
public static void main(String[] args) throws IOException {
JavaReaderFiles readFile = new JavaReaderFiles();
// read using buffer reader
readFile.readFileUsingBufferReader();
//read using FileChannel
readFile.readFileUsingFileChannel();
//read using DataInputStream
readFile.readFileUsingDataInputStream();
// using scanner
readFile.readFileUsingScanner();
// read file using tokenizer
readFile.readFileStreamTokenizer();
// read file with UTF-8 data
readFile.readUTF8FileData();
}
}

View File

@@ -0,0 +1,88 @@
package com.javadevjournal.read.file;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
public class JavaReaderFiles {
private final String FILE_LOCATION = "src/main/resources/read_java_file.txt";
private final String STREAMTOKENIZER_FILE_LOCATION = "src/main/resources/stream_tokenizer_read_java_file.txt";
private final String UTF8_FILE_LOCATION = "src/main/resources/special_char_data.txt";
public void readFileUsingBufferReader() throws IOException {
BufferedReader bufferedReader = new BufferedReader(new FileReader(FILE_LOCATION));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
// perform your logic with the data
System.out.println(line);
}
}
public void readFileUsingFileChannel() throws IOException {
RandomAccessFile file = new RandomAccessFile(FILE_LOCATION, "r");
FileChannel channel = file.getChannel();
int bufferSize = 1024;
ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
while (channel.read(buffer) != -1) {
System.out.println(new String(buffer.array()));
}
channel.close();
file.close();
}
public void readFileUsingDataInputStream() throws IOException {
DataInputStream dataInputStream = new DataInputStream(new FileInputStream(FILE_LOCATION));
while (dataInputStream.available() > 0) {
System.out.println(dataInputStream.readUTF());
}
}
public void readFileUsingScanner() throws IOException {
Scanner scanner = new Scanner(new File(FILE_LOCATION), StandardCharsets.UTF_8.name());
scanner.useDelimiter("\\n");
while (scanner.hasNext()) {
// perform your logic with the data
System.out.println(scanner.next());
}
}
public void readFileStreamTokenizer() throws IOException {
// init the file and StreamTokenizer
FileReader reader = new FileReader(STREAMTOKENIZER_FILE_LOCATION);
StreamTokenizer tokenizer = new StreamTokenizer(reader);
// we will iterate through the output until end of file
while (tokenizer.nextToken() != StreamTokenizer.TT_EOF) {
// we will work on the data based on the data type
if(tokenizer.ttype == StreamTokenizer.TT_WORD) {
System.out.println(tokenizer.sval);
} else if(tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
System.out.println(tokenizer.nval);
} else if(tokenizer.ttype == StreamTokenizer.TT_EOL) {
System.out.println();
}
}
}
public void readUTF8FileData() throws IOException {
// create a Buffer reader without encoding and pass encoding information
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(UTF8_FILE_LOCATION)));
String line;
// we iterate until EOF
while ((line = bufferedReader.readLine()) != null) {
// perform your logic with the data
System.out.println(line);
}
// close the buffer
bufferedReader.close();
}
}

View File

@@ -0,0 +1,64 @@
package com.javadevjournal.read.file;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class ReadDataWithJava7 {
private static final String FILE_LOCATION = "src/main/resources/read_java_file.txt";
public static void main(String[] args) {
String output = readFileReadAllBytes(FILE_LOCATION);
//System.out.println(output);
output = readFileBufferReader(FILE_LOCATION);
System.out.println(output);
}
/*
Internal method to read the data from the file using readAllBytes method
*/
private static String readFileReadAllBytes(final String path){
// define a data holder to store the data read from the file
String data="";
try
{
data = new String ( Files.readAllBytes( Paths.get(path) ) );
}
catch (IOException e)
{
e.printStackTrace();
}
return data;
}
/*
Read files using the new Files class and BufferReader option
*/
private static String readFileBufferReader(final String filePath){
// define a data holder to store the data read from the file
Path path = Paths.get(filePath);
StringBuilder fileContent = new StringBuilder();
try {
BufferedReader br= Files.newBufferedReader(path);
String line ;
while ((line = br.readLine()) != null) {
// perform your logic with the data
fileContent.append(line);
}
}
catch (IOException e)
{
e.printStackTrace();
}
return fileContent.toString();
}
}

View File

@@ -0,0 +1,49 @@
package com.javadevjournal.read.file;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class ReadFileUsingJava8 {
private static final String FILE_LOCATION = "src/main/resources/read_java_file.txt";
public static void main(String[] args) throws IOException {
readLineByLine(FILE_LOCATION);
readWithBuilder(FILE_LOCATION);
}
/*
This method read the file line by line using Java 8 stream API
*/
private static void readLineByLine(final String fileLocation) throws IOException {
// create the path
Path path = Paths.get(fileLocation);
try(Stream<String> stream = Files.lines(path)){
// read one line ar a time
stream.forEach(System.out::println);
}
}
/*
Read all content line by line but add them to a StringBuilder
*/
private static void readWithBuilder(final String fileLocation) throws IOException {
StringBuilder sb = new StringBuilder();
// create the path
Path path = Paths.get(fileLocation);
try(Stream<String> stream = Files.lines(path)){
// read one line ar a time
stream.forEach(s-> sb.append(s).append("/n"));
}
System.out.println(sb.toString());
}
}

View File

@@ -0,0 +1,3 @@
This file contains data to test
the different ways to read file in
Java.

View File

@@ -0,0 +1,2 @@
目前美国有50个州以及1个联邦区
在这50个州中有48个是连续的也就是说它们是直接连接的

View File

@@ -0,0 +1,2 @@
Currently, the US has 50 states as well as 1 federal district
Of these 50 states, 48 of them are contiguous, that is, they are connected directly.