一、IO流是什么?
基于字节流和字符流进行操作
二、IO流分类
1、按照流的方向:
流向内存 :input 输入 , read 读;
流向硬盘: output输出, writer 写;
2、按照流分类:
- 输入流,
- 输出流,
- 字符流(字符是读取文件中每个字符例如:a啊ba 一次一次读需要四次),字符流主要的方法:java.io.Reader 字符输入流,java.io.Writer 字符输出流
- 字节流(子节流则是按字节来读 中文需要读取两次),字节流主要的方法:java.io.InputStream 字节输入流,java.io.OutputStream 字节输出流
三 File文件的简单操作做、
1、文件写入硬盘的方法:
-
方法一 new File(String path)
// 方法1 new File(String path) @Test public void created1(){ String filePath = "d:\\newFile.txt"; //文件位置 File file = new File(filePath); try { file.createNewFile();//使用createFile方法创建文件 } catch (IOException e) { e.printStackTrace(); } }
- 方式二 new File(File parent ,String child) 根据父文件目录+子路径构建
@Test //方式二 new File(File parent ,String child) 根据父文件目录+子路径构建 public void created2(){ File parentFile = new File("d:\\"); String fileName = "new2.txt"; File file = new File(parentFile,fileName);//文件只是创建在内存当中,并没有在硬盘上,这个File对象,在Java程序中只是一个对象 try { file.createNewFile();//这个是写入硬盘 } catch (IOException e) { e.printStackTrace(); } }
- 方法三 new File(String parent, String path)
@Test public void created3(){ String parent = "d:\\"; String filePath = "newFile1.txt"; //文件位置 File file = new File(parent,filePath); try { file.createNewFile();//使用createFile方法创建文件 } catch (IOException e) { e.printStackTrace(); } }
2、File文件的基本方法:
getName | 文件名 |
getAbsolutePath | 文件绝对路径 |
getParent | 文件父目录 |
length | 文件字节长度 |
exists | 文件是否存在 |
isFile | 是不是个文件 |
isDirectory | 是不是个目录 |
@Test
// 获取文件信息
public void info(){
// 先创建文件对象
File file = new File("d:\\new2.txt");
// 文件对应的方法 getName, getAbsolutePath, getParent, length, exists, isFile, isDirectory
// 调用对应的方法,得到对应信息
System.out.println("文件名=" + file.getName());
System.out.println("文件绝对路径=" + file.getAbsolutePath());
System.out.println("文件父目录=" + file.getParent());
System.out.println("文件字节长度" + file.length());
System.out.println("文件是否存在" + file.exists());
System.out.println("是不是个文件" + file.isFile());
System.out.println("是不是个目录" + file.isDirectory());
}
}
总结
简单写一下基本的使用