How to read File?
Read Text File
There are different ways to read file in java:
1. Using Buffered Reader
If you want to read file line by line then you should use Buffered Reader and its S
Example
package com.IOFile;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
public class ReadFileUsingBufferedReader {
public static void main(String[] args) throws IOException {
String file_Name = "/home/codersarts/output.txt";
File file = new File(file_Name);
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
String one_line;
while((one_line = br.readLine()) != null){
System.out.println(one_line);
}
br.close();
}
}
2. Using Scanner
If you want to read line by line from the file on basis of some expression like A Boy is wrtten in the file read this line by space seperated then you can use this Scanner class. This scanner breaks the line into tokens after that we can save it itno any String array . This is not Synchronized and not thread safe.
Example
package com.IOFile;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class ReadFileUsingScanner {
public static void main(String[] args) throws IOException {
String file_Name = "/home/codersarts/output.txt";
File file = new File(file_Name);
Scanner scanner = new Scanner(file);
System.out.println("Read text file using Scanner line by line");
//read line by line
while(scanner.hasNextLine()){
//process each line
String one_line = scanner.nextLine();
System.out.println(one_line);
}
scanner.close();
}
}
3. Using File Reader
Example
package com.IOFile;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class ReadFileUsingFileReader {
public static void main(String[] args) throws IOException {
String file_Name = "/home/codersarts/output.txt";
File file = new File(file_Name);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String one_line;
System.out.println("Reading text file using FileReader line by line");
while((one_line = br.readLine()) != null){
//process the line
System.out.println(one_line);
}
br.close();
fr.close();
}
}
4. Using java.nio.file.Files
This is used when you want data on memory or we can say in our program like below examples and it should be used for small files Files class method readAllBytes read file data by byte array ( means 1 Line take it from file and make it 1 byte array).
Example
package com.IOFile;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class FileReadUsingFilesClass {
public static void main(String[] args) throws IOException {
String file_Name = "/home/codersarts/output.txt";
Path path = Paths.get(file_Name);
//read file to byte array
byte[] bytes = Files.readAllBytes(path);
System.out.println("Read text file using Files class");
//read file to String list
@SuppressWarnings("unused")
List < String> allLines = Files.readAllLines(path, StandardCharsets.UTF_8);
System.out.println(new String(bytes));
}
}
Read CSV File
Example
package com.IOFile;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ReadCSVFile {
public static void main(String[] args) throws IOException {
// open file input stream
BufferedReader reader = new BufferedReader(new FileReader(
"student.csv"));
// read file line by line
String line = null;
Scanner scanner = null;
int index = 0;
List< Student> studentList = new ArrayList< Student>();
while ((line = reader.readLine()) != null) {
Student student = new Student();
scanner = new Scanner(line);
scanner.useDelimiter(",");
while (scanner.hasNext()) {
String data = scanner.next();
if (index == 0)
student.setName(data);
else if (index == 1)
student.setCourse(data);
else if (index == 2)
student.setId(Integer.parseInt(data));
else if (index == 3)
student.setAge(Integer.parseInt(data));
else
System.out.println("invalid data::" + data);
index++;
}
index = 0;
studentList.add(student);
}
//close reader
reader.close();
for(Student s : studentList )
System.out.println(s);
}
}
Output
Student id=100, age=26, name=Akriti, course=Btech
Student id=101, age=28, name=Ankit, course=MCA
Student id=102, age=27, name=Shrishti, course=Btech
Student id=103, age=28, name=Sushil, course=MCA
Student id=104, age=26, name=Naveen, course=MBA
Download File From URL
Example
package com.IOFile;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
public class DownloadFileFromURL {
public static void main(String[] args) {
String dir_Name = "/home/coders/Desktop";
String url = "https://github.com/notepad-plus-plus/notepad-plus-plus/releases/download/v7.8.2/npp.7.8.2.bin.zip";
try {
System.out.println("Downloaded file from github using java file IO");
System.out.println("---------------------------");
// Using java IO
downloadFileFromUrlWithJavaIO(dir_Name + "/notepad1.zip",url);
System.out.println("Downloading file from github using apache common IO");
System.out.println("---------------------------");
// Using Apache common IO
downloadFileFromUrlWithCommonsIO(dir_Name + "/notepad2.zip",url);
System.out.println("Downloading file from github using NIO");
System.out.println("---------------------------");
// Using NIO
downloadFileFromURLUsingNIO(dir_Name + "/notepad3.zip",url);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// Using Java IO
public static void downloadFileFromUrlWithJavaIO(String fileName, String fileUrl)
throws MalformedURLException, IOException {
BufferedInputStream inStream = null;
FileOutputStream outStream = null;
try {
URL fileUrlObj=new URL(fileUrl);
inStream = new BufferedInputStream(fileUrlObj.openStream());
outStream = new FileOutputStream(fileName);
byte data[] = new byte[1024];
int count;
while ((count = inStream.read(data, 0, 1024)) != -1) {
outStream.write(data, 0, count);
}
} finally {
if (inStream != null)
inStream.close();
if (outStream != null)
outStream.close();
}
}
// Using common IO
public static void downloadFileFromUrlWithCommonsIO(String fileName,
String fileUrl) throws MalformedURLException, IOException {
FileUtils.copyURLToFile(new URL(fileUrl), new File(fileName));
}
// Using NIO
private static void downloadFileFromURLUsingNIO(String fileName,String fileUrl) throws IOException {
URL url = new URL(fileUrl);
ReadableByteChannel rbc = Channels.newChannel(url.openStream());
FileOutputStream fOutStream = new FileOutputStream(fileName);
fOutStream.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fOutStream.close();
rbc.close();
}
}
Output
Downloading file from github using java file IO
Downloaded file from github using java file IO
Downloading file from github using apache common IO
Downloaded file from github using NIO