Java 流概述
文件通常是由一连串的字节或字符构成,组成文件的字节序列称为字节流,组成文件的字符序列称为字符流。Java 中根据流的方向可以分为输入流和输出流。输入流是将文件或其它输入设备的数据加载到内存的过程;输出流恰恰相反,是将内存中的数据保存到文件或其他输出设 备
- 流:数据在数据源文件和程序内存直接经历的路径
- 输入流:数据从数据源文件到程序内存的路径
- 输出流:数据从程序内存到数据源文件的路径
常用文件操作
创建文件方法
- new File(String pathname) :根据路径构建一个File对象
- new File(File parent,Sring child):根据父目录文件+子路径构建
- new File(String parent,String child):根据父目录+子路径构建
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| public class FileCreate { public static void main(String[] args) {} @Test public void create01() { String filePath = "e:\\news1.txt"; File file = new File(filePath); try { file.createNewFile(); System.out.println("文件创建成功"); } catch (IOException e) { e.printStackTrace(); } } @Test public void create02() { File parentFile = new File("e:\\"); String fileName = "news2.txt"; File file = new File(parentFile, fileName); try { file.createNewFile(); System.out.println("创建成功~"); } catch (IOException e) { e.printStackTrace(); } } @Test public void create03() { String parentPath = "e:\\"; String fileName = "news4.txt"; File file = new File(parentPath, fileName); try { file.createNewFile(); System.out.println("创建成功~"); } catch (IOException e) { e.printStackTrace(); } } }
|
获取文件相关信息
- getName 文件名字
- getAbsolutePath 文件绝对路径
- getParent 文件父级目录
- length 文件大小(字节)
- exists 文件是否存在
- isFile 是不是一个文件
- isDirectory 是不是一个目录
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| public class FileInformation { public static void main(String[] args) {} @Test public void info() { File file = new File("e:\\news1.txt"); 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()); } }
|
目录的操作和文件删除
- mkdir 创建一级目录
- mkdirs 创建多级目录
- delete 删除空目录或文件
流的分类
|
字节流 |
字符流 |
输入流 |
InputStream |
Reader |
输出流 |
OutputStream |
Writer |
InputStream抽象类式所有类字节输入流的超类
- FileInputStream:文件输入流
- BufferedInputStream:缓冲字节输入流
- ObjectlnputStream:对象字节输入流