Multiple ways to read files in java 1. Read file contents in multiple ways.
1. Read file contents by bytes
2. Read file content by character
3. Read file contents line by line
4. Randomly read file contents
*/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.io.Reader;
public class ReadFromFile {
/**
* Read files in bytes, often used to read binary files, such as pictures, sounds, images, etc.
* @param fileName The name of the file
*/
public static void readFileByBytes(String fileName){
File file = new File(fileName);
InputStream in = null;
try {
System.out.println("Read the file content in bytes, one byte at a time:");
//Read one byte at a time
in = new FileInputStream(file);
int tempbyte;
while((tempbyte=in.read()) != -1){
System.out.write(tempbyte);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
return;
}
try {
System.out.println("Read the file content in bytes, multiple bytes at a time:");
//Read multiple bytes at a time
byte[] tempbytes = new byte[100];
int byteread = 0;
in = new FileInputStream(fileName);
ReadFromFile.showAvailableBytes(in);
//Read multiple bytes into the byte array, byteread is the number of bytes read at one time
while ((byteread = in.read(tempbytes)) != -1){
System.out.write(tempbytes, 0, byteread);
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (in != null){
try {
in.close();
} catch (IOException e1) {
}
}
}
}
/**
* Read files in character units, often used to read text, numbers and other types of files
* @param fileName file name
*/
public static void readFileByChars(String fileName){
File file = new File(fileName);
Reader reader = null;
try {
System.out.println("Read the file content in character units, one byte at a time:");
//Read one character at a time
reader = new InputStreamReader(new FileInputStream(file));
int tempchar;
while ((tempchar = reader.read()) != -1){
//For Windows, when the two characters rn are together, they represent a newline.
//But if these two characters are displayed separately, the lines will be changed twice.
//Therefore, shield r, or shield n. Otherwise, there will be a lot of blank lines.
if (((char)tempchar) != 'r'){
System.out.print((char)tempchar);
}
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
System.out.println("Read the file content in character units, multiple bytes at a time:");
//Read multiple characters at once
char[] tempchars = new char[30];
int charread = 0;
reader = new InputStreamReader(new FileInputStream(fileName));
//Read multiple characters into the character array, charread is the number of characters read at a time
while ((charread = reader.read(tempchars))!=-1){
//Similarly shield r from displaying
if ((charread == tempchars.length)&&(tempchars[tempchars.length-1] != 'r')){
System.out.print(tempchars);
}else{
for (int i=0; i<charread; i++){
if(tempchars[i] == 'r'){
continue;
}else{
System.out.print(tempchars[i]);
}
}
}
}
} catch (Exception e1) {
e1.printStackTrace();
}finally {
if (reader != null){
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
/**
* Read files in line units, often used to read line-oriented formatted files
* @param fileName file name
*/
public static void readFileByLines(String fileName){
File file = new File(fileName);
BufferedReader reader = null;
try {
System.out.println("Read the file content in line units, reading a whole line at a time:");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
//Read one line at a time until null is read as the end of the file
while ((tempString = reader.readLine()) != null){
//display line number
System.out.println("line " + line + ": " + tempString);
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null){
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
/**
* Randomly read file contents
* @param fileName file name
*/
public static void readFileByRandomAccess(String fileName){
RandomAccessFile randomFile = null;
try {
System.out.println("Read a random file content:");
// Open a random access file stream in read-only mode
randomFile = new RandomAccessFile(fileName, "r");
//File length, number of bytes
long fileLength = randomFile.length();
//Read the starting position of the file
int beginIndex = (fileLength > 4) ? 4 : 0;
//Move the starting position of the read file to the beginIndex position.
randomFile.seek(beginIndex);
byte[] bytes = new byte[10];
int byteread = 0;
//Read 10 bytes at a time. If the file content is less than 10 bytes, read the remaining bytes.
//Assign the number of bytes read at a time to byteread
while ((byteread = randomFile.read(bytes)) != -1){
System.out.write(bytes, 0, byteread);
}
} catch (IOException e){
e.printStackTrace();
} finally {
if (randomFile != null){
try {
randomFile.close();
} catch (IOException e1) {
}
}
}
}
/**
* Display the number of bytes remaining in the input stream
* @param in
*/
private static void showAvailableBytes(InputStream in){
try {
System.out.println("The number of bytes in the current byte input stream is:" + in.available());
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String fileName = "C:/temp/newTemp.txt";
ReadFromFile.readFileByBytes(fileName);
ReadFromFile.readFileByChars(fileName);
ReadFromFile.readFileByLines(fileName);
ReadFromFile.readFileByRandomAccess(fileName);
}
}
2. Append content to the end of the file
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* Append content to the end of the file
*/
public class AppendToFile {
/**
*A method to append files: use RandomAccessFile
* @param fileName file name
* @param content additional content
*/
public static void appendMethodA(String fileName,
String content){
try {
// Open a random access file stream, in read and write mode
RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
//File length, number of bytes
long fileLength = randomFile.length();
//Move the write file pointer to the end of the file.
randomFile.seek(fileLength);
randomFile.writeBytes(content);
randomFile.close();
} catch (IOException e){
e.printStackTrace();
}
}
/**
* Method B to append files: use FileWriter
* @param fileName
* @param content
*/
public static void appendMethodB(String fileName, String content){
try {
//Open a file writer. The second parameter true in the constructor means writing the file in append form.
FileWriter writer = new FileWriter(fileName, true);
writer.write(content);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String fileName = "C:/temp/newTemp.txt";
String content = "new append!";
//Append files according to method A
AppendToFile.appendMethodA(fileName, content);
AppendToFile.appendMethodA(fileName, "append end. n");
//Display file content
ReadFromFile.readFileByLines(fileName);
//Append files according to method B
AppendToFile.appendMethodB(fileName, content);
AppendToFile.appendMethodB(fileName, "append end. n");
//Display file content
ReadFromFile.readFileByLines(fileName);
}
}