------- android培训、java培训、期待与您交流! ----------
这里的文件流泛指一系列java.io包中操作文件的类的统称。
import java.io.File; public class FileStream { public static void main(String[] args) { //File既可以将已存在的文件封装成对象,也可以将不存在的文件封装成对象 File f1=new File("c:\\abc\\a.txt"); //File类的构造函数既可以接受完整路径,也可以接受相对路径 File f2=new File("a.txt"); //File类还有一种构造方法,可以接收两个参数,一个是目录路径,一个是文件名 File f3=new File("c:\\abc","c.txt"); File f4=new File("c:\\abc"); File f5=new File(f4,"c.txt"); System.out.println(f1); System.out.println(f2); System.out.println(f3); System.out.println(f4); System.out.println(f5); } }上面的程序输出结果为:
import java.io.File; import java.io.IOException; public class FileDemo { public static void main(String[] args) { File f1=new File("readme.txt"); try { System.out.println(f1.createNewFile());//true System.out.println(f1.createNewFile());//false System.out.println(f1.delete());//true System.out.println(f1.delete());//false } catch (IOException e){ e.printStackTrace(); } } }
File f2=new File("hello.txt"); System.out.println(f2.exists());//false System.out.println(f2.isFile());//false System.out.println(f2.isDirectory());//false System.out.println(f2.isAbsolute());//false try { System.out.println(f2.createNewFile());//true System.out.println(f2.isFile());//true System.out.println(f2.isDirectory());//false System.out.println(f2.isAbsolute());//false } catch (IOException e){ e.printStackTrace(); }注意hello.txt也有可能是文件夹,如下图所示
public static void method3(){ File f1=new File("test.txt");//这个文件在硬盘上存在 System.out.println(f1.getName());//test.txt System.out.println(f1.getPath());//test.txt System.out.println(f1.getParent());//null System.out.println(f1.getAbsolutePath());//D:\Code\Java\javaenhance\test.txt System.out.println(f1.lastModified());//1419651154909 System.out.println(showDate(f1.lastModified()));//2014-32-27 11:32:34 System.out.println(f1.length());//27 File f2=new File("abc\\test.txt");//这个文件在硬盘上不存在 System.out.println(f2.getName());//test.txt System.out.println(f2.getPath());//abc\test.txt System.out.println(f2.getParent());//abc System.out.println(f2.getAbsolutePath());//D:\Code\Java\javaenhance\abc\test.txt System.out.println(f2.lastModified());//0 System.out.println(f2.length());//0 } public static String showDate(long millisecond){ Date date=new Date(millisecond); SimpleDateFormat simple=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return simple.format(date); }上面代码中右边的注释是运行结果,之所以为静态是方便在java主函数中调用.
public static void method7(){ File f1=new File("c:\\Test.java");//文件存在 File f2=new File("d:\\haha.java");//文件不存在 System.out.println(f1.renameTo(f2));//返回剪切是否成功 }
public static void method4(){ File[] files=File.listRoots(); for (File f : files) { System.out.println(f); } }运行结果:
public static void method5(){ File file=new File("F:\\"); //调用list方法的File必须封装的是一个目录并且该目录在硬盘上存在,否则返回空指针异常 String[] namesStrings=file.list(); for (String name : namesStrings) { System.out.println(name); } }
public static void main(String[] args) { showDir(new File("F:\\Mytreasure\\study\\java")); } public static void showDir(File dir){ System.out.println(dir.getAbsolutePath()); File[] files=dir.listFiles(); for (File file : files) { if (file.isDirectory()) { showDir(file); }else { System.out.println(file.getAbsolutePath()); } } }注意上面的代码中使用了递归算法来遍历目录和目录中的目录。
public class RecursionDemo { public static void main(String[] args) { toBin(44115); } public static void toBin(int decimal){ if (decimal>0) { toBin(decimal/2); System.out.print(decimal%2); } } }再举一例,用代码计算公差为1,首项为n,尾项为1的等差数列
public static void main(String[] args) { System.out.println(getSum(1000)); } public static int getSum(int n){ if (n==1) { return 1; }else { return getSum(n-1)+n; } }上面的例子要注意,当给getSum函数传过大的数值参数时,可能造成内存溢出,所以递归算法要注意 递归次数不要太多。
import java.io.File; public class FileOther { public static void main(String[] args) { showDir(new File("F:\\Mytreasure\\study\\java"),0); } public static String getIndent(int level){ StringBuffer sb=new StringBuffer(); for (int i = 0; i < level; i++) { sb.append("|--"); } return sb.toString(); } public static void showDir(File dir,int level){ System.out.println(getIndent(level)+dir.getAbsolutePath()); level++; File[] files=dir.listFiles(); for (File file : files) { if (file.isDirectory()) { showDir(file,level); }else { System.out.println(getIndent(level)+file.getAbsolutePath()); } } } }主要就是加了个生成多级缩进的方法。
public static void main(String[] args) { boolean a=deleteDir(new File("F:\\1")); if (a) { System.out.println("删除成功"); }else { System.out.println("删除失败"); } } /** * 递归删除指定目录中的所有目录和文件 * @param dir 指定目录 * @return true为删除成功,false为删除失败 */ public static boolean deleteDir(File dir){ boolean isSuccess=true; File[] files=dir.listFiles(); for (File file : files) { if (file.isDirectory()) { isSuccess=deleteDir(file); if (!isSuccess) { return false; } }else { isSuccess= file.delete(); if (!isSuccess) { return false; } } } isSuccess=dir.delete(); if (!isSuccess) { return false; } return true; }上面的代码递归删除文件夹和其中的所有东西,注意递归层层传递返回值的技巧,这个是视频中没讲到的。
package File; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.*; /** * 对指定目录建立一个java文件列表,并保存到文件中 * 思路: * 1.递归遍历指定目录 * 2.递归过程中获取该目录的所有Java文件的路径 * 3.将路径保存到集合中 * 4.把集合中的数据输出到文件中 */ public class JavaFileList { public static void main(String[] args) { File dir=new File("F:\\Mytreasure\\study\\java\\3GetStarted"); List<File> list=new ArrayList<File>(); RecursionToGetPath(dir, list); File targetFile=new File("F:\\Mytreasure\\study\\java\\javaList.txt"); listToFile(list,targetFile); } public static void RecursionToGetPath(File dir,List<File> list){ File[] files=dir.listFiles(); for (File file : files) { if (file.isDirectory()) { RecursionToGetPath(file, list); }else { if (file.getAbsolutePath().endsWith(".java")){ list.add(file); } } } } public static void listToFile(List<File> list,File targetFile){ BufferedWriter bfwr=null; try { bfwr=new BufferedWriter(new FileWriter(targetFile)); for (File file : list) { bfwr.write(file.toString()); bfwr.newLine(); bfwr.flush(); } } catch (IOException e) { throw new RuntimeException(e); } finally { try { if (bfwr != null) bfwr.close(); } catch (IOException e) { throw new RuntimeException(e); } } } }
package File; import java.util.Properties; import java.util.Set; public class PropertiesDemo { public static void main(String[] args) { Properties prop=new Properties(); //保存键值对 prop.setProperty("张三", "24岁"); prop.setProperty("李四", "20岁"); System.out.println(prop);//{张三=24岁, 李四=20岁} //根据键获取值 System.out.println(prop.getProperty("张三"));//24岁 //根据键修改值 prop.setProperty("李四", "40岁"); System.out.println(prop.getProperty("李四"));//40岁 //获取所有键 Set<String> keys=prop.stringPropertyNames(); for (String key : keys) { System.out.println(key+":"+prop.getProperty(key)); } } }上面的代码输出:
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; import java.util.Set; public class PropertiesDemo { public static void main(String[] args) { saveAndLoad(); } public static void saveAndLoad(){ Properties prop=new Properties(); prop.setProperty("jdk", "1.6"); prop.setProperty("os", "windows 8"); //将Properties对象的数据写入到文件中 FileOutputStream fos=null; try { fos=new FileOutputStream("F:\\Mytreasure\\study\\java\\testData\\PropertyContent.ini"); prop.store(fos, "create property file"); } catch (IOException e) { throw new RuntimeException(e); } finally { try { if (fos != null) fos.close(); } catch (IOException e) { throw new RuntimeException(e); } } //通过Properties读取数据 FileInputStream fis=null; try { fis=new FileInputStream("F:\\Mytreasure\\study\\java\\testData\\PropertyContent.ini"); prop.load(fis); System.out.println(prop); } catch (IOException e) { throw new RuntimeException(e); } finally { try { if (fis != null) fis.close(); } catch (IOException e) { throw new RuntimeException(e); } } //通过Properties修改数据 prop.setProperty("os", "window 10"); //将Properties对象的数据写入到文件中 try { fos=new FileOutputStream("F:\\Mytreasure\\study\\java\\testData\\PropertyContent.ini"); prop.store(fos, "edit data"); } catch (IOException e) { throw new RuntimeException(e); } finally { try { if (fos != null) fos.close(); } catch (IOException e) { throw new RuntimeException(e); } } } }练习:用配置文件存储程序运行次数,当运行5次后,提醒用户程序运行次数已到
public static void calculate(){ Properties prop=new Properties(); File file=new File("F:\\Mytreasure\\study\\java\\testData\\count.ini"); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { throw new RuntimeException(e); } } FileInputStream fis=null; FileOutputStream fos=null; try { fis=new FileInputStream(file); prop.load(fis); String str=prop.getProperty("count"); int count=0; if (str!= null) { count=Integer.parseInt(str); if (count>=5) { System.out.println("您的使用次数已到,请注册软件"); return; } } count++; prop.setProperty("count", count+""); fos=new FileOutputStream(file); prop.store(fos, ""); } catch (IOException e) { throw new RuntimeException(e); } finally { try { if (fis != null) fis.close(); if (fos != null) fos.close(); } catch (IOException e) { throw new RuntimeException(e); } } }
import java.io.BufferedReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; public class PrintWriterDemo { public static void main(String[] args) { BufferedReader bufr=null; PrintWriter pw=null; try { bufr=new BufferedReader(new InputStreamReader(System.in)); pw=new PrintWriter(new FileWriter("a.txt"),true); String line=""; while((line=bufr.readLine())!=null){ if("over".equals(line)) break; pw.println(line.toUpperCase()); } } catch (IOException e) { throw new RuntimeException(e); } finally { try { if (bufr != null) bufr.close(); if (pw != null) pw.close(); } catch (IOException e) { throw new RuntimeException(e); } } } }