1Java I/O 概览
1.1 文件系统和File类
Java中的File类。在java.io包中。对于一个File对象来说,它能够代表硬盘上的一个群文件或文件夹。
- File对象不仅能代表一个文件夹。还能代表一个文件对象
- File对象是“代表”一个文件或者文件夹
File 类的构造方法:
- File(String pathname):利用字符串作为参数,表示一个路径名。用来创建一个代表给定参数的文件或者文件夹。
- File(String parent,String child):parent 表示父目录,child表示在parent目录下的路径。这种写法用来代表名字为parent/child的文件或者文件夹。
- File(File parent,String chile):同样用parent表示父类目录,只不过这个parent是用File类型来表示。
注意:
创建File对象的时候,需要指定文件的路径,指定的时候,可以用绝对路径,也可以用相对路径
在Windows中,路径分隔符使用的是反斜杠“\”,而在java中反斜杠是用来转义的,因此要使用反斜杠的话,必须使用"\"来表示一个反斜杠。
例:
"D:\\abc"
也可以用一个正斜杠用来做Windows中的路径分离,这样就不需要转义。
例:
"D:/abc"
File的基本操作
createNewFile():可以用来创建一个新文件。需要注意的是,如果这个文件在系统中已经存在,createNewFile方法不会覆盖原有文件。
例:createNewFile
public class Mkdir {
public static void main(String[] args) {
String path = "E:/test/text.txt";
File dir = new File(path);
try {
dir.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("创建成功");
}
}
结果为:
mkdir()/mkdirs():这俩个方法都可以用来创建文件夹。所不同的是,mkdir只能创建一层文件夹,而mkdir能够创建多层文件夹
例:mkdir
public class Mkdir {
public static void main(String[] args) {
String path = "E:/test/def";
File dir = new File(path);
dir.mkdir();
System.out.println("创建成功");
}
}
结果为:
例:mkdirs
public static void createFiles(){
String path = "E:/test/a/b/c";
File dir = new File(path);
dir.mkdirs();
System.out.println("创建成功");
}
delete():可以删除File所代表的文件或者文件夹。
public static void main(String[] args) {
String path = "E:/test/def/text.txt";
File dir = new File(path);
dir.delete();
System.out.println("删除成功");
}
运行前:
运行后:
常见方法
createNewFile():创建文件
mkdirs():创建目录
exists():判断文件是否存在
isDirectory():是否是文件夹
getName():获得文件名称
getAbsolutePath():获得绝对路径
length():获得文件的字节数
delete():删除文件
rename(File newFile):重命名文件
list():获得目录的下一级全部文件的名称数组
listFiles(): 获得目录下 子文件文件数组。
流
什么是流
流Stream 表示数据传输的一种方式,把数据从内存写到文件或者从文件读取到内存。
流的分类
- 按方向
- 输入流:将**<存储设备>中的内容读写到<内存>**中
- 输出流:将**<内存>中的内容写入到<存储设备>**中
读入写入
- 按单位
- 字节流:以字节为单位,可以读写所有的数据
- 字符流:以字符为单位,只能读写文本数据
字节流 是最基础的流,处理字节,传输 二进制文件,如视频 …字符流 主要处理文本数据传输。
- 按功能
- 节点流:具有时机传输数据的读写功能
- 过滤流:在节点基础上增强功能
- 字节输入流:
- 抽象类: OutputStream
- 字类文件:FileOutputStream
FileOutputStream (“D:/abc/python.txt”)如果文件不存在或创建文件,如果文件目录不存在会报错
FileOutputStream (“python.txt”)使用相对路径会创建在工程目录中
FileOutputStream (“python.txt”,true),以追加的方式写文件
public class FileOutputStreamDemo{
public static void (String[] args){
//创建一条流
OutputStream os = new FileOutputStream("D:/python.txt",true);
//写数据
String py = "你要悄悄学python";
os.write(py.getBytes());
System.out.println("over");
}
}
- 字节输入流
-抽象类: InputStream- 字类:FileInputStream
public static void main(String[] args) throws IOException {
InputStream is = new FileInputStream("E:/test/name.txt") ;
byte[] bs = new byte[1024];
int n = 0;
while ((n = is.read(bs)) != -1 ){
String ss = new String(bs,0,n);
System.out.println(ss);
}
is.close();
}
- FileOutputStream 文件(字节)输出流
public static void main(String[] args) throws Exception {
//创建一条流
OutputStream os = new FileOutputStream("python.txt",true);
String py = "然后惊艳所有人";
//写数据
os.write( py.getBytes() );
System.out.println("over");
//关闭流
os.close();
}
FileOutputStream(“文件名.txt”,true) 表示以追加方式打开文件
- FileInputStream 文件(字节)输入流
public static void main(String[] args) throws IOException {
//创建流
InputStream is = new FileInputStream("python.txt");
//读取
//1 准备字节数组
byte[] bs = new byte[1024];
//2 读取数据
int n=0;//计数器,保存读到的个数
while( (n=is.read(bs))!=-1 ) {
//读取到的内容转换成字符串
String ss = new String(bs,0,n);// 把有效数据转行成字符串
System.out.println(ss);
}
//关闭流
is.close();
}
- 字节流复制文件
public class Copy{
InputStream fis = new FileInputSream("test.txt");
OutputStream fos = new FileOutputStream("copy_test.txt");
byte[] bs = new byte[1024];
int n = 0;
while((n = fis.read(bs))!=-1){
fos.write(bs,0,n);
}
fis.colse();
fos.colse();
}
- BufferedOutputStream 字节输出缓冲流
public static void main(String[] args) throws Exception {
// 缓冲流
FileOutputStream fos = new FileOutputStream("d:/nb.txt",true);
BufferedOutputStream bos = new BufferedOutputStream( fos );
//写
bos.write( "关注我每天学一套穿搭".getBytes() );
//刷新缓冲区的数据到文件
bos.flush();
//关闭流
bos.close();
System.out.println("gg");
}
- BufferedInputStream 字节输入缓冲流
public static void main(String[] args) throws IOException {
// 1 创建流
FileInputStream fis = new FileInputStream("d:/nb.txt") ;
BufferedInputStream bis = new BufferedInputStream( fis );
// 2 准备容器 计数器
byte[] bs = new byte[1024];
int len;
// 4 读取数据
String all="";
while( ( len= bis.read(bs)) !=-1 ) {
String temp = new String(bs, 0, len);
all+=temp;
}
System.out.println(all);
// 5 关闭
bis.close();
}
- 字符缓冲流 文件复制
public class Copy{
public static void main(String[] args) throws IOException{
//创建输入流,用于读文件
BufferIuputStream bis = new BufferIuputStream(new FileInputStream("test.txt"));
//创建流,用于写文件
BufferOutputStream bos = new BufferOutputStream(new FileOutputStream("test1.txt"));
//定义接受的一次数量
char[] ch = new char[1024];
//计数
int n = 0;
//循环
while((n = bis.read(ch))!=-1){
//写
bos.read(ch,0,n);
}
bos.flush();
bos.close();
bis.close();
}
}
- ObjectOutputStream 对象输出流
/**
*
* ObjectOutputStream : 对象(字节)输出流
*
* 把一个内存中对象 通过IO流 持久化 保存 这个过程叫做序列化
* 1、 类型需要 实现 Serializable
* 2、 属性类型也要 是可序列化的
* 3、transient 不参与序列化
*
*/
public class TestObjectOutputStream {
public static void main(String[] args) throws IOException{
//1. 创建流
ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream("data.dat") );
//2. 写对象
Student obj1 = new Student("阿立", 28 ,new Obj("小红", 28) );
Student obj2 = new Student("阿美", 30,new Obj("小美", 28));
Student obj3 = new Student("阿华", 31,new Obj("大乔", 28));
List<Student> list = new ArrayList<>();
list.add(obj1);
list.add(obj2);
list.add(obj3);
oos.writeObject(list);
//3 刷新
oos.flush();
//4 关闭
oos.close();
}
}
- ObjectInputStream 对象输入流
/** ObjectInputStream : 对象(字节)输入流*/
public static void main(String[] args) throws Exception {
//创建流读对象
ObjectInputStream ois = new ObjectInputStream( new FileInputStream("data.dat") );
//读取对象
List<Student> list = (List<Student>) ois.readObject();
for(Student st:list) {
System.out.println(st);
}
//关闭
ois.close();
}
反序列化 需要注意 知道 序列化顺序 和 个数,可以使用集合序列化,然后反序列化
- Writer 字符输出流
write(char[] chs)
write(String str)
- Reader 字符输入流
read(char[] )
- FileWriter 文件(字符)输出流
public static void write(String msg, String path ) throws IOException {
//1. 创建流
Writer writer = new FileWriter( path, true );
//2. 写
writer.write(msg);
//3. 关闭
writer.close();
}
- FileReader 文件(字符)输入流
public static String read( String path ) throws IOException {
//1 创建流
Reader reader = new FileReader(path);
//2 准备容器 准备计数器
char[] chs = new char[1024];
int len;
//3 循环读
StringBuilder sb = new StringBuilder();
while( (len = reader.read(chs) )!=-1 ) {
// 把读到了字符转成字符串
String ss = new String(chs, 0, len);
sb.append(ss);
}
//4 关闭流
return sb.toString();
}
- BufferedReader 字符输入缓冲流
public static String read(String path) throws IOException {
//创建流
BufferedReader reader = new BufferedReader( new FileReader(path) );
//读文件
String line;
StringBuilder sb = new StringBuilder();
while( (line=reader.readLine()) !=null ) {
sb.append(line);
}
//关闭
reader.close();
return sb.toString();
}
- BufferedWriter 字符输出缓冲流
public static void write(String info, String path) throws IOException {
//创建
BufferedWriter writer = new BufferedWriter(new FileWriter(path,true));
//写数据
writer.write(info);
//写入一个换行符
writer.newLine();
//刷新
writer.flush();
//关闭流
writer.close();
}
输入流 读 InputStream read
输出流 写 OutputStream write
输入流使用
1实例化一个输入流对象
InputStream is = new FileInputStream("xx.txt");
2.用什么数组去接受读到的值
byte(字节输入流) char(字符输入流) String(字符输入缓冲流)
byte[] bs = new byte[1024];
3.定义一个变量去接受读取到的长度,字符输入缓冲流不用
int n = 0;
4.while(变量赋值便判断不为-1,字符输入缓冲赋值判断是否为null)
while((n = is.read(bs))!=-1)
5.用一个字符串的构造方法去接受读出来的值
String ss = new String(bs,0,n);
6.关闭流
注:
对象输入流接受需要实现序列化,实现Serializable 接口
需要用对象接受
读入的是对象
如果使用的是集合,读入的也是集合
输出流
1.创建一个输出流OutputStream
2.向指定文件写入数据,若指定文件不在,会自动创建文件
3.关闭流,缓冲流需要先使用flush()将缓冲区的数据推到文件中,再关闭
-
桥转换流
将字节流转换为字符流- OutputStreamWriter
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("test.txt")));
bw.write("ssssssssssssssssssssssssssssssssss");
bw.newLine();
bw.flush();
bw.close();
- InputStreamReader
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("test.txt")));
String line;
while ((line = br.readLine())!=null){
System.out.println(line);
}
- printStream
字符过滤流- 封装了print()/println()方法,支持写入后换行
- 支持数据原样打印
PrintStream ps = new PrintStream("test.txt");
ps.println("sssssssssssssssssssssssssssss");
ps.close();
- Scanner
Scanner sc = new Scanner(new File("test.txt"));
while (sc.hasNextLine()){
String ss = sc.nextLine();
System.out.println(ss);
}