85.文件
文件流:文件在程序中是以流的形式来操作的
流:数据在数据源(文件)和程序(内存)之间经理的路程
流的输入与输出是按java程序来分辨的,从java程序出去的就是输出流
常用的文件操作:
new File(String pathname) //根据路径构建一个File对象 new File(File parent,String child) //根据父目录文件+子路径构建 new File(String parent,String child) //根据父目录+子路径构建 createNewFile //创建新文件 //方式1:new File(String pathname) @Test public void create01(){ String filePath = "d:\\news1.txt"; File file = new File(filePath); try { file.createNewFile(); System.out.println("文件创建成功"); } catch (IOException e) { throw new RuntimeException(e); } } //方式2:new File(File parent,String child) @Test public void create02(){ File parentFile = new File("d:\\"); String fileName = "news2.txt"; File file = new File(parentFile, fileName);//此操作只是在内存中创建了对象,与硬盘无交互 try { file.createNewFile();//此时才将信息写入到硬盘 System.out.println("文件创建成功"); } catch (IOException e) { throw new RuntimeException(e); } } //方式3:new File(String parent,String child) @Test public void create03(){ String parentPath = "d:\\"; String fileName = "news3.txt"; File file = new File(parentPath, fileName); try { file.createNewFile(); System.out.println("创建成功"); } catch (IOException e) { throw new RuntimeException(e); } } }
获取文件相关信息:
file.getName(); //文件名字 file.getAbsolutePath //文件绝对路径 file.getParent //文件父目录 file.getlength //文件大小 file.exists //是否存在 file.isFile //是否是文件 file.isDirectory //是否是目录
目录操作:
mkdir //创建一级目录 mkdirs //创建多级目录 delete //删除空目录或文件
86.IO流原理和分类
-
I/O是Input/Output的缩写,I/O技术是非常实用的技术,用于处理数据传输。如读/写,网络通讯等
-
Java程序中,对于数据的输入/输出操作以“流”的方式进行
-
Java.io包下提供了各种“流”类和接口,用以获取不同种类的数据,并通过方法输入或输出数据
-
输入input:读取外部数据(磁盘、光盘等存储谁被的数据)到程序中
-
输出output:将程序数据输出到磁盘,光盘等存储设备中
流的分类:
按操作数据单位不同分为:字节流(8bit),字符流(按字符)
按数据流的流向不同分为:输入流,输出流
按流的角色的不同分为:节点流,处理流/包装流