1.字符输入流 FileReader
常用方法:
创建对象 new FileReader(File/String)
每次读取单个字符,返回该字符,若到文件末尾返回-1 read()
批量读取多个字符到数组,返回读取到的字符数,到文件末尾返回-1 read(char[])
将char[]转换为String:new String(char[]) 将char[]的指定部分转换为String:new String(char[], off, len)
import org.junit.jupiter.api.Test;
import java.io.FileReader;
import java.io.IOException;
public class FileReader_ {
public static void main(String[] args) {
}
@Test
public void readFile01(){
String filePath = "D:\\test1.txt";
FileReader fileReader = null;
int data = 0;
try {
fileReader = new FileReader(filePath);
while((data = fileReader.read()) != -1){
System.out.print((char) data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(fileReader != null){
fileReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void readFile02(){
String filePath = "D:\\test1.txt";
FileReader fileReader = null;
int readLen = 0;
char[] buf = new char[8];
try {
fileReader = new FileReader(filePath);
while((readLen = fileReader.read(buf)) != -1){
System.out.print(new String(buf, 0, readLen));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(fileReader != null){
fileReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2.字符输出流 FileWriter
常用方法:
创建对象 new FileWriter(File/String) 覆盖,流的指针在首段 new FileWriter(File/String, true) 追加,流的指针在尾端
写入单个字符 write(int)
写入指定数组 write(char[])
写入指定数组的指定部分 write(char[], off, len)
写入整个字符串 write(string)
写入字符串的指定部分 write(string, off, len)
FileWriter使用后,必须关闭close或刷新flush,否则写入不到指定的文件
import org.junit.jupiter.api.Test;
import java.io.FileWriter;
import java.io.IOException;
public class FileWriter_ {
public static void main(String[] args) {
}
@Test
public void fileWriter01(){
String filePath = "D:\\daily.txt";
FileWriter fileWriter = null;
char[] chars = {'q','w','e','r'};
String string = " this is note";
try {
fileWriter = new FileWriter(filePath);
fileWriter.write('Y');
fileWriter.write(chars);
fileWriter.write(chars, 0, 1);
fileWriter.write(string);
fileWriter.write(string, 0, 0);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
|