Java基础知识系列——文件操作

  对文件进行操作在编程中比较少用,但是我最近有一个任务需要用到对文件操作。

  对文件有如下操作形式:

  1.创建新的文件(夹)

    File fileName = new File("C:/myfile.txt");

    fileName.createNewFile(); //创建文件

    File fileName = new File("C:/myfile");

    fileName.mkdir(); //创建文件夹

  2.对比两个文件路径

    fileName.compareTo(anotherFileName);

  3.获取文件的最后修改日期

    fileName.lastModified(); //返回类型是long

  4.在指定目录下创建文件

    File file = null;

    File dir = new File("C:/"):

    file = File.creatTempFile("javeTemp",".javatemp",dir);

    file.getPath(); //获取文件路径

  5.判断文件是否存在

    file.exists();

  6.设置文件只读与可写

    file.setReadOnly(); //只读

    file.setWrite(); //可写

  7.文件重命名

    File oldName = new File("C:/program.txt");

    File newName = new File("C:/java.txt");

    oldName.renameTo(newName);

  8.文件大小

    file.exists(); //是否存在

    file.isFile(); //是否是文件

    file.length(); //获取文件大小

  9.改变文件最后修改时间

    file.setLastModified( System.currentTimeMills());

  10.创建临时文件

    File temp = File.createTempFile( "pattern", ".suffix");

    temp.deleteOnExit();

    BufferedWriter out = new BufferedWriter( new FileWriter( temp));

    out.write( "aString");

  11.在现有文件最后添加字符串

    BufferedWriter out = new BufferedWriter( new FileWriter( "fileName"));

    out.write( "aString1");

    out.close();

    out = new BufferedWriter( new FileWriter( "fileName"; true));

    out.writer();

    out.close();

  12.复制文件

    BufferedWriter out1 = new BufferedWriter( new FileWriter( "srcFile"));

    out1.write( "String to be copied");

    out1.close();

    InputStream in = new FileInputStream( new File( "srcFile"));

    OutputStream out = new OutputStream( new File( "destnFile"));

    byte[] buf = new byte[1024];

    int len = 0;

    while( ( len = in.read( buf)) > 0){

      out.write( buf, 0, len);

    }

    in.close();

    out.close();

  13.删除文件

    file.delete(); //返回类型是boolean

  14.读取文件

    BufferedReader in = new BufferedReader( new FileReader( "C:/fileName"));

    String str = "":

    while( ( str = in.readLine()) != null){

      System.out.println( str);

    }

  15.写入文件

    BufferedWriter out = new BufferedWriter( new FileWriter( "outFileName"));

    out.write( "aString");

    out.close();  //一定要记得关闭,一定要管关

 

原文:http://www.yiibai.com/javaexamples/java_files.html

posted @ 2016-12-04 21:17  aston  阅读(229)  评论(0编辑  收藏  举报