Java编程中最基础的文件和目录操作方法详解

 更新时间:2015年11月17日 08:46:50   作者:小李飞刀8  
这篇文章主要介绍了Java编程中最基础的文件和目录操作方法详解,是Java入门学习中的基础知识,需要的朋友可以参考下

文件操作

平常经常使用JAVA对文件进行读写等操作,这里汇总一下常用的文件操作。

1、创建文件

public static boolean createFile(String filePath){ 
  boolean result = false; 
  File file = new File(filePath); 
  if(!file.exists()){ 
    try { 
      result = file.createNewFile(); 
    } catch (IOException e) { 
      e.printStackTrace(); 
    } 
  } 
   
  return result; 
} 

2、创建文件夹

public static boolean createDirectory(String directory){ 
  boolean result = false; 
  File file = new File(directory); 
  if(!file.exists()){ 
    result = file.mkdirs(); 
  } 
   
  return result; 
} 

3、删除文件

public static boolean deleteFile(String filePath){ 
  boolean result = false; 
  File file = new File(filePath); 
  if(file.exists() && file.isFile()){ 
    result = file.delete(); 
  } 
   
  return result; 
} 

4、删除文件夹

递归删除文件夹下面的子文件和文件夹

public static void deleteDirectory(String filePath){ 
  File file = new File(filePath); 
  if(!file.exists()){ 
    return; 
  } 
   
  if(file.isFile()){ 
    file.delete(); 
  }else if(file.isDirectory()){ 
    File[] files = file.listFiles(); 
    for (File myfile : files) { 
      deleteDirectory(filePath + "/" + myfile.getName()); 
    } 
     
    file.delete(); 
  } 
} 

5、读文件

(1)以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件

public static String readFileByBytes(String filePath){ 
  File file = new File(filePath); 
  if(!file.exists() || !file.isFile()){ 
    return null; 
  } 
   
  StringBuffer content = new StringBuffer(); 
   
  try { 
    byte[] temp = new byte[1024]; 
    FileInputStream fileInputStream = new FileInputStream(file); 
    while(fileInputStream.read(temp) != -1){ 
      content.append(new String(temp)); 
      temp = new byte[1024]; 
    } 
     
    fileInputStream.close(); 
  } catch (FileNotFoundException e) { 
    e.printStackTrace(); 
  } catch (IOException e) { 
    e.printStackTrace(); 
  } 
   
  return content.toString(); 
} 

 (2)以字符为单位读取文件,常用于读文本,数字等类型的文件,支持读取中文

public static String readFileByChars(String filePath){ 
  File file = new File(filePath); 
  if(!file.exists() || !file.isFile()){ 
    return null; 
  } 
   
  StringBuffer content = new StringBuffer(); 
  try { 
    char[] temp = new char[1024]; 
    FileInputStream fileInputStream = new FileInputStream(file); 
    InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "GBK"); 
    while(inputStreamReader.read(temp) != -1){ 
      content.append(new String(temp)); 
      temp = new char[1024]; 
    } 
     
    fileInputStream.close(); 
    inputStreamReader.close(); 
  } catch (FileNotFoundException e) { 
    e.printStackTrace(); 
  } catch (IOException e) { 
    e.printStackTrace(); 
  } 
   
  return content.toString(); 
} 

(3)以行为单位读取文件,常用于读面向行的格式化文件

public static List<String> readFileByLines(String filePath){ 
  File file = new File(filePath); 
  if(!file.exists() || !file.isFile()){ 
    return null; 
  } 
   
  List<String> content = new ArrayList<String>(); 
  try { 
    FileInputStream fileInputStream = new FileInputStream(file); 
    InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "GBK"); 
    BufferedReader reader = new BufferedReader(inputStreamReader); 
    String lineContent = ""; 
    while ((lineContent = reader.readLine()) != null) { 
      content.add(lineContent); 
      System.out.println(lineContent); 
    } 
     
    fileInputStream.close(); 
    inputStreamReader.close(); 
    reader.close(); 
  } catch (FileNotFoundException e) { 
    e.printStackTrace(); 
  } catch (IOException e) { 
    e.printStackTrace(); 
  } 
   
  return content; 
} 

6、写文件

字符串写入文件的几个类中,FileWriter效率最高,BufferedOutputStream次之,FileOutputStream最差。

(1)通过FileOutputStream写入文件

public static void writeFileByFileOutputStream(String filePath, String content) throws IOException{ 
  File file = new File(filePath); 
  synchronized (file) { 
    FileOutputStream fos = new FileOutputStream(filePath); 
    fos.write(content.getBytes("GBK")); 
    fos.close(); 
  } 
} 

(2)通过BufferedOutputStream写入文件

public static void writeFileByBufferedOutputStream(String filePath, String content) throws IOException{ 
  File file = new File(filePath); 
  synchronized (file) { 
    BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(filePath)); 
    fos.write(content.getBytes("GBK")); 
    fos.flush(); 
    fos.close(); 
  } 
} 

(3)通过FileWriter将字符串写入文件

public static void writeFileByFileWriter(String filePath, String content) throws IOException{ 
    File file = new File(filePath); 
    synchronized (file) { 
      FileWriter fw = new FileWriter(filePath); 
      fw.write(content); 
      fw.close(); 
    } 
  } 

目录操作
目录是一个文件可以包含其他文件和目录的列表。你想要在目录中列出可用文件列表,可以通过使用 File 对象创建目录,获得完整详细的能在 File 对象中调用的以及有关目录的方法列表。

创建目录
这里有两个有用的文件方法,能够创建目录:

mkdir( ) 方法创建了一个目录,成功返回 true ,创建失败返回 false。失败情况是指文件对象的路径已经存在了,或者无法创建目录,因为整个路径不存在。
mkdirs( ) 方法创建一个目录和它的上级目录。
以下示例创建 “/ tmp / user / java / bin” 目录:

import java.io.File;

public class CreateDir {
  public static void main(String args[]) {
   String dirname = "/tmp/user/java/bin";
   File d = new File(dirname);
   // Create directory now.
   d.mkdirs();
 }
}

编译并执行以上代码创建 “/ tmp /user/ java / bin”。

提示:Java 自动按 UNIX 和 Windows 约定来处理路径分隔符。如果在 Windows 版本的 Java 中使用正斜杠(/),仍然可以得到正确的路径。

目录列表
如下,你能够用 File 对象提供的 list() 方法来列出目录中所有可用的文件和目录

import java.io.File;

public class ReadDir {
  public static void main(String[] args) {

   File file = null;
   String[] paths;

   try{   
     // create new file object
     file = new File("/tmp");

     // array of files and directory
     paths = file.list();

     // for each name in the path array
     for(String path:paths)
     {
      // prints filename and directory name
      System.out.println(path);
     }
   }catch(Exception e){
     // if any error occurs
     e.printStackTrace();
   }
  }
}

基于你/ tmp目录下可用的目录和文件,将产生以下结果:

test1.txt
test2.txt
ReadDir.java
ReadDir.class

相关文章

  • IDEA安装lombok插件设置Enable Annotation Processing后编译依然报错解决方法

    IDEA安装lombok插件设置Enable Annotation Processing后编译依然报错解决方法

    这篇文章主要介绍了IDEA安装lombok插件设置Enable Annotation Processing后编译依然报错解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-04-04
  • Spring的同一个服务会加载多次的问题分析及解决方法

    Spring的同一个服务会加载多次的问题分析及解决方法

    这篇文章主要介绍了Spring的同一个服务为什么会加载多次,我们先来梳理一下 Web 容器中如何加载 Bean,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-10-10
  • 详解Java中List接口底层实现原理

    详解Java中List接口底层实现原理

    Java是一种广泛应用的编程语言,被广泛应用于各种平台和应用领域,List接口是Java中最重要的数据结构之一,它为我们提供了一种灵活、高效、可扩展的数据结构,本篇文章将首先介绍Java中List接口的基本特性和使用方法,然后深入研究List接口的底层实现原理
    2023-11-11
  • Java设计模式之模板模式(Template模式)介绍

    Java设计模式之模板模式(Template模式)介绍

    这篇文章主要介绍了Java设计模式之模板模式(Template模式)介绍,定义一个操作中算法的骨架,将一些步骤的执行延迟到其子类中,需要的朋友可以参考下
    2015-03-03
  • 如何使用JAVA调用SHELL

    如何使用JAVA调用SHELL

    这篇文章主要介绍了如何使用JAVA调用SHELL,文中讲解非常细致,代码帮助大家更好的理解和学习,感兴趣的朋友可以了解下
    2020-06-06
  • GateWay动态路由与负载均衡详细介绍

    GateWay动态路由与负载均衡详细介绍

    这篇文章主要介绍了GateWay动态路由与负载均衡,GateWay支持自动从注册中心中获取服务列表并访问,即所谓的动态路由
    2022-11-11
  • Java日常练习题,每天进步一点点(63)

    Java日常练习题,每天进步一点点(63)

    下面小编就为大家带来一篇Java基础的几道练习题(分享)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧,希望可以帮到你
    2021-08-08
  • Java继承构造器使用过程解析

    Java继承构造器使用过程解析

    这篇文章主要介绍了Java继承构造器使用过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-12-12
  • 使用kotlin编写spring cloud微服务的过程

    使用kotlin编写spring cloud微服务的过程

    这篇文章主要介绍了使用kotlin编写spring cloud微服务的相关知识,本文给大家提到配置文件的操作代码,给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-09-09
  • java实现快速排序算法

    java实现快速排序算法

    快速排序算法是基于分治策略的另一个排序算法。其基本思想是:对输入的子数组a[p:r],按以下三个步骤进行排序。 1) 分解(Divide)(2) 递归求解(Conquer) (3) 合并(Merge)
    2015-04-04

最新评论