1、文件
2、IO流
InputStream,OutputStream,Reader,Writer都是抽象类
3、FileInputStream BufferedInputStream ObjectInputStream
(1) FileInputStream 字节输入流
package test9;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Field;
public class test {
public static void main(String[] args) throws IOException {
//如果文本文件中:含有文字 用字节流可能会乱码
String filePath="D:\\hello.txt";
//字节数组
byte[] buf = new byte[1024];
int readLen = 0;
FileInputStream fileInputStream = null;
try {
fileInputStream=new FileInputStream(filePath);
//如果返回-1,表示读取完毕
//如果读取正常,返回实际读取的字节数
while ((readLen = fileInputStream.read(buf)) != -1) {
System.out.print(new String(buf, 0, readLen));
}
} catch (IOException e) {
e.printStackTrace();
}finally {
//关闭文件流,释放资源。
try {
fileInputStream.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
}
文本文件用字符流
(2)字节流FileOutputStream 字节输出流
@Test
public void writeFile(){
//创建 FileOutputStream对象
String filePath="d:\\a.txt";
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(filePath);
//写入字符串
String str = "hello,world! 张吉林";
fileOutputStream.write(str.getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭文件流,释放资源。
try {
fileOutputStream.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
(3) 字符流 FileReader FileWriter
(4)节点流和处理流
节点流:效率较低
处理流:效率更高11
(5) BufferedWriter BufferedReader 专门处理字符
package test9;
import org.junit.Test;
import java.io.*;
import java.nio.Buffer;
import java.nio.charset.StandardCharsets;
public class test1 {
public static void main(String[] args) {
// 说明
// 1、BufferedReader 和 BufferedWriter 是按照字符操作
// 2、不要去操作二进制文件,可能造成文件损坏
String srcFilePath = "d:\\a.java";
String destFilePath = "d:\\a2.java";
BufferedReader br = null;
BufferedWriter bw = null;
String line;
try {
br = new BufferedReader(new FileReader(srcFilePath));
bw = new BufferedWriter(new FileWriter(destFilePath));
//说明:readLine 读取一行内容,但是没有换行
while ((line = br.readLine()) != null) {
//每读取一行,就写入
bw.write(line);
//插入一个换行
bw.newLine();
}
System.out.println("文件拷贝成功");
}catch (IOException e){
e.printStackTrace();
}finally {
//关闭流
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
(5) ObjectInputStream ObjectOutputStream 处理流 专门处理对象
dog对象需要实现序列化接口:
(6) InputStreamReader OutputStreamWriter 转换流
(7) Properties 配置文件读取和写入