接下来,老蝴蝶带着大家学习一下 IO 流。 学习IO 流之前,一定要先学习一下,关于文件 File 的操作。
我们平常常说的文件File 和目录 Directory 都使用 java.io.File 类进行表示。
一. File 类的两个静态系统常量
一.一 方法
一.二 演示
/** * 测试路径常量 */ @Test public void pathTest(){ //windows 系统为 ; linux为 : System.out.println("路径分隔符:"+File.pathSeparator); // windows 系统为 \, linux 为 / System.out.println("文件分隔符:"+File.separator); }
控制台打印输出:
路径拼接时,为了避免系统差异,应该用常量去连接路径。 (系统常量小写,是Java 历史原因。)
二. File 的构造方法
二.一 方法
二.二 演示
/** * 测试构造方法 */ @Test public void contrTest(){ //1. 最常用的还是第一种, 绝对路径 File file1=new File("E:"+File.separator+"ideaWork"+File.separator+"Java2"+File.separator+"fileSrc" +File.separator+"Hello.txt"); System.out.println("文件1内容长度:"+file1.length()); // 以 src 开头, 传入相对路径 File file11=new File("src"+File.separator+"Hello.txt"); System.out.println("文件11内容长度:"+file11.length()); // 2. 父路径 和 当前文件名 File file2=new File("E:"+File.separator+"ideaWork"+File.separator+"Java2"+File.separator+"fileSrc","Hello.txt"); System.out.println("文件2内容长度:"+file2.length()); //3. 父文件和 当前文件名 File parent=new File("E:"+File.separator+"ideaWork"+File.separator+"Java2"+File.separator+"fileSrc"); File file3=new File(parent,"Hello.txt"); System.out.println("文件3大小:"+file3.length()); //4. 网络路径 file:/E:.... 具体的路径 URL url= null; try { url = new URL("file:"+File.separator+"E:"+File.separator+"ideaWork"+File.separator +"Java2"+File.separator+"fileSrc" +File.separator+"Hello.txt"); } catch (MalformedURLException e) { e.printStackTrace(); } File file4= null; try { file4 = new File(url.toURI()); } catch (URISyntaxException e) { e.printStackTrace(); } System.out.println("文件4大小:"+file4.length()); }
控制台打印输出:
三. 文件的基本操作
包括 文件的创建,文件的删除,判断文件是否存在,文件的重命名。
三.一 方法
三.二 演示
/** * 创建,删除,判断是否存在,重命名 操作。 */ @Test public void operTest() throws Exception{ //1. 定义一个文件, 没有这个文件 File file=new File("E:"+File.separator+"ideaWork"+File.separator+"Java2"+File.separator+"fileSrc" +File.separator+"Hello2.txt"); //如果文件存在 if(file.exists()){ //删除文件 //file.delete(); //定义新的文件 File newFile=new File("E:"+File.separator+"ideaWork"+File.separator+"Java2"+File.separator+"fileSrc" +File.separator+"HelloNew2.txt"); //重命名文件, 文件的内容依旧保存。 file.renameTo(newFile); }else{ //创建文件 file.createNewFile(); } }
运行程序,文件系统进行查看。 刚开始是没有这个文件 Hello2.txt 的。
第一次运行前:
第一次运行后:
再一次运行:
发现,成功 重命名了。 如果是重命名的话, 那么文件的内容依旧还是在的。
如果执行 file.delete() 的操作,那么会发现,文件成功删除了。