创建一个文件
1 String s="d:\Test.txt"; //在D盘下创建一个Test文件 .txt为后缀 2 File f=new File(s); //构建一个文件对象。此时没有执行 3 f.createNewFile(); //创建一个新文件
创建文件夹
1 String mulu="d:\Test"; //在d盘下创建名为Test 的文件夹 2 File wj=new File(mulu); 3 wj.mkdir();
删除文件或文件夹
1 String f="d:\Test"; //删除文件夹 2 //String f="d:\Test.txt"; //删除文件 3 File s=new File(f); 4 s.delete();
将文件夹下的文件夹或者子文件夹列出来
1 String s="f:\英雄联盟"; 2 File f=new File(s); 3 File[] list = f.listFiles(); //获取到的值放到数组中,用for循环,将其打印出来 4 for (int i=0; i<list.length;i++){ 5 //String n=list[i].getName(); //getName()获取当前文件夹下所有的文件名 6 String n=list[i].getPath(); //getPath()带有文件夹路径 7 8 if(list[i].isDirectory()){ //isDirectory()判断是否为文件夹 9 System.out.print("【目录】"); 10 } 11 else if(list[i].isFile()){ //isFile()判断是否为文件 exists()判断是否有该文件或路径是否存在 12 System.out.print("【文件】"); 13 } 14 System.out.println(n); 15 }
重命名或者移动文件(将原文件删除,重新建一个文件出来)
1 String a="d:\Test1.txt"; 2 String b="d:\Test10.txt"; 3 File m=new File(a); 4 File n=new File(b); 5 m.renameTo(n);
读、写 字符流
1 //写入 字符流 2 String ad="d:\Test.txt"; 3 FileWriter w=new FileWriter(ad,true);//括号中如果只有一个参数,则覆盖,逗号后加true 即追加,在其后面追加,不覆盖 4 w.write("Hello Word"); 5 w.close(); 6 7 //读取 字符流 8 String a="d:\Test.txt"; 9 File n=new File(a); 10 FileReader reader=new FileReader(n); 11 char[] s=new char [(int) n.length()]; 12 reader.read(s); 13 String str =new String(s); 14 System.out.println(str); 15 reader.close();
读取结果略
2017-03-02