字符输入流:Reader
操作步骤
步骤1:打开字符读操作流,可能会抛出FileNotFoundException异常
FileReader reader = new FileReader(path);
步骤2:读操作,可能会抛出IOException异常
reader.read();
步骤3:关闭字符读操作流
reader.close();
常用方法介绍:
int read() :
每次读取一个字符,读操作结束的返回值-1,返回值就是字符对应的ASCII码的数字
int read(char cbuf[]):
批量读取数据,读操作结束的返回值-1,数据读取到char []数组中,返回值表示读取有效数据个数
int read(char cbuf[], int offset, int length):
批量读取数据,读操作结束的返回值-1,数据读取到char []数组中,可以指定读取数据的起始和大小,返回值表示读取有效数据的个数
public static void reader() {
String path = "/Users/gongdezhe/Desktop/test.txt";
//reader字符流的读操作基类 ==>读取文件-》FileReader
//步骤
//步骤1:打开字符读操作流,可能会抛出FileNotFoundException异常
try {
FileReader reader = new FileReader(path);
//步骤2:读操作,可能会抛出IOException异常
reader.read();
//字符输入流方法介绍 读操作结束的返回值-1
//int read() 每次读取一个字符,返回值就是字符对应的ASCII码的数字
reader.read();
//int read(char cbuf[]) 批量读取数据,数据读取到char []数组中,返回值表示读取有效数据个数
char[] chars = new char[100];
reader.read(chars);
//int read(char cbuf[], int offset, int length)批量读取数据,数据读取到char []数组中,
//可以指定读取数据的起始和大小,返回值表示读取有效数据个数
reader.read(chars, 0 ,9);
reader.mark(4);
reader.markSupported();
reader.reset();
/*CharBuffer allocate = CharBuffer.allocate(1024);
// CharBuffer charBuffer = new CharBuffer();
reader.read(allocate);
allocate.flip();
char[] chars1 = new char[allocate.remaining()];
allocate.get(chars1);
String s = new String(chars1);
System.out.println(s);*/
//步骤3:关闭字符读操作流
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
练习:文件复制功能实现指定一个文件,将其复制到指定路径下
public static void main(String[] args) throws IOException {
String srcPath = "C:\\Users\\lenovo\\Desktop\\a.txt";
String decPath = "C:\\Users\\lenovo\\Desktop\\b.txt";
copyFile(srcPath,decPath);
}
public static void copyFile(String srcPath,String decPath) throws IOException {
//打开读写流
FileInputStream in = new FileInputStream(srcPath);
FileOutputStream out = new FileOutputStream(decPath);
//进行读写
/* //读法一
int byt = 0;
while((byt = in.read()) != -1){
out.write(byt);
}*/
/*//读写二
int byt = 0;
byte[] bytes = new byte[5];
while((byt = in.read(bytes)) != -1) {
out.write(bytes,0,byt);
}*/
/* //错误实例 abcdef 文件缺一半
int byt = 0;
byte[] bytes = new byte[5];
while(in.read(bytes)!=-1){
out.write(byt);
}*/
//错误实例 文件读取不完善
int byt = 0;
byte[] bytes = new byte[5];
in.read();
out.write(bytes);
//关闭流
in.close();
out.close();
}
}