java 實現以字元為單位讀取檔案(3)
阿新 • • 發佈:2019-02-07
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
public class readFile2 {
/**
* 以字元為單位讀取檔案,常用於讀文字,數字等型別的檔案
*/
public static void readFileByChars(String fileName) {
File file = new File(fileName);
Reader reader = null ;
try {
System.out.println("以字元為單位讀取檔案內容,一次讀一個字元:");
// 一次讀一個字元
reader = new InputStreamReader(new FileInputStream(file));
int tempchar;
while ((tempchar = reader.read()) != -1) {
// 對於windows下,rn這兩個字元在一起時,表示一個換行。
// 但如果這兩個字元分開顯示時,會換兩次行。
// 因此,遮蔽掉r,或者遮蔽n。否則,將會多出很多空行。
if (((char) tempchar) != 'r') {
System.out.print((char) tempchar);
}
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
System.out.println("以字元為單位讀取檔案內容,一次讀多個字元:");
// 一次讀多個字元
char[] tempchars = new char[30];
int charread = 0;
reader = new InputStreamReader(new FileInputStream(fileName));
// 讀入多個字元到字元陣列中,charread為一次讀取字元數
while ((charread = reader.read(tempchars)) != -1) {
// 同樣遮蔽掉r不顯示
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) {
}
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String filePath="F:\\test\\testR.txt";
//在F盤建立test資料夾,在資料夾下建立testR.txt檔案
readFileByChars(filePath);
}
}