zoukankan      html  css  js  c++  java
  • Java-File类

     1 import java.io.File;
     2 import java.io.IOException;
     3 /**
     4  * 文件基本操作
     5  */
     6 public class FileTest {
     7     public static void main(String[] args) {
     8         //根据路径,创建一个文件对象
     9         File file = new File("E:/printTest.txt");
    10         //该文件对象提供了对文件判断和操作的方法
    11         //判断文件是否存在
    12         if(file.exists()) {
    13             //文件重命名
    14             file.renameTo(new File("E:/print.txt"));
    15             //同分区之间的移动
    16             file.renameTo(new File("E:/test/print.txt"));
    17             //判断是否为文件
    18             Boolean flag = file.isFile(); 
    19             System.out.println(flag);
    20             //判断是否为文件夹
    21             Boolean flag1 = file.isDirectory(); 
    22             System.out.println(flag1);
    23             //删除文件
    24             file.delete(); 
    25         }else {
    26             try {
    27                 //如果不存在该文件,则可以根据路径创建文件
    28                 file.createNewFile();
    29             } catch (IOException e) {
    30                 e.printStackTrace();
    31             }
    32         }
    33     }
    34 }
     1 import java.io.File;
     2 /**
     3  * 文件常用属性
     4  */
     5 public class FileTest1 {
     6     public static void main(String[] args) {
     7         File file = new File("E:/print.txt");
     8         boolean exists = file.exists();                    //文件是否存在
     9         boolean directory = file.isDirectory();         //是否为文件夹
    10         boolean canRead = file.canRead();                 //文件是否可读
    11         boolean canWrite = file.canWrite();             //文件是否可写
    12         String name = file.getName();                    //文件名称
    13         String path = file.getPath();                    //文件路径
    14         String absolutePath = file.getAbsolutePath();    //文件的绝对路径
    15         
    16         // 文件的父级路径
    17         // 当创建的file上一级目录为空时返回null   例如:File file = new File("test.txt");
    18         String parent = file.getParent();
    19         // 通过以下方式可以获取文件的绝对路径,然后在获取父级路径
    20         String parent2 = new File(absolutePath).getParent();
    21 
    22         long size = file.length();// byte
    23         float size1 = (float)file.length()/1000;// KB
    24         // 文件是否被隐藏  linux中文件以.开头则为隐藏   window中查看文件属性查看是否隐藏
    25         boolean hidden = file.isHidden(); 
    26     }
    27 }
     1 import java.io.File;
     2 
     3 /**
     4  * 文件读写属性
     5  */
     6 public class FileTest2 {
     7     public static void main(String[] args) {
     8         File file = new File("E:/print.txt");
     9         
    10         file.setWritable(true);//设置可写
    11         file.setWritable(false);//设置不可写
    12         
    13         file.setReadable(true);//设置可读
    14         file.setReadable(false);//设置不可读
    15         
    16         file.setReadOnly();//设置只读
    17     }
    18 }
     1 import java.io.File;
     2 /**
     3  * 遍历文件夹
     4  */
     5 public class FileTest3 {
     6     public static void main(String[] args) {
     7         printFiles(new File("E:/test/"),1);
     8     }
     9     public static void printFiles(File dir,int tab) {
    10         if(dir.isDirectory()) {//判断是否为文件夹
    11             File[] listFiles = dir.listFiles();//获取文件夹中所有的文件
    12             //遍历获取的所有文件
    13             for (int i = 0; i < listFiles.length; i++) {
    14                 for (int j = 0; j < tab; j++) {
    15                     System.out.print("|--");//目录结构的分隔符
    16                 }
    17                 System.out.println(listFiles[i].getName());
    18                 //判断遍历的元素是否为文件夹,如果是则继续调用printFiles()方法
    19                 if(listFiles[i].isDirectory()) {
    20                     printFiles(listFiles[i],tab+1);
    21                 }
    22             }
    23         }
    24     }
    25 }
     1 import java.io.File;
     2 import java.io.IOException;
     3 import java.nio.file.Path;
     4 
     5 /**
     6  * File类方法介绍
     7  */
     8 public class FileTest4 {
     9     public static void main(String[] args) throws IOException {
    10         File file = new File("E:\test\");
    11         
    12         System.out.println(File.separator);//文件的路径分隔符
    13         
    14         //路径操作
    15         System.out.println(file.getName());//如果该路径为文件,则获取文件名称,如果是目录,则获取目录名
    16         System.out.println(file.getParent());//获取父级路径的字符串
    17         System.out.println(file.getParentFile());//获取父级路径的File对象
    18         System.out.println(file.getPath());//获取抽象路径为字符串路径
    19         System.out.println(file.toURI());//将抽象路径转成uri    file:/E:/test/2/1.txt
    20         
    21         System.out.println(file.getAbsolutePath());//获取绝对路径的字符串路径,如果抽象路径不是绝对路径,则默认添加上工程路径
    22         System.out.println(file.getAbsoluteFile());//获取绝对路径后转成File
    23         System.out.println(file.getCanonicalPath());//返回规范路径字符串格式
    24         System.out.println(file.getCanonicalFile());//返回规范路径File对象
    25         
    26         //判断
    27         System.out.println(file.isAbsolute());//判断是否为绝对路径
    28         System.out.println(file.canRead());//判断是否可读
    29         System.out.println(file.canWrite());//判断是否可写
    30         System.out.println(file.canExecute());//是否可执行;
    31         System.out.println(file.exists());//判断是否存在
    32         System.out.println(file.isDirectory());//判断是否为目录
    33         System.out.println(file.isFile());//判断是否为文件
    34         System.out.println(file.isHidden());//判断是否隐藏
    35         
    36         //文件访问权限设置
    37         file.setReadOnly();//设置文件只读
    38         file.setReadable(true);//设置文件可读
    39         file.setReadable(true, true);//第一个是否可读,第二个是否只读
    40         file.setWritable(true);//设置文件可写
    41         file.setWritable(true, true);//文件只写,第一个是否可写,第二个是否只写
    42         file.setExecutable(true);//设置文件可执行
    43         file.setExecutable(true, true);//第一个是否可执行,第二个文件所属者可执行
    44 
    45         //最后一次修改时间的获取和设置
    46         System.out.println(file.lastModified());//获取文件最后修改时间
    47         System.out.println(file.setLastModified(123456L));//设置文件最后一次修改时间
    48         
    49         System.out.println(file.length());//如果是文件,则返回文件内容大小字节数,如果是目录则返回0
    50         
    51         //创建目录
    52         file.mkdir();//如果抽象路径是目录,则创建该目录
    53         file.mkdirs();//创建多级目录,包含父级目录,如果创建失败,可能已经创建了父级目录
    54         File.createTempFile("aaa", ".temp", file);//指定前缀和后缀,根据File的抽象路径目录,创建临时文件
    55         
    56         //创建文件和删除
    57         System.out.println(file.createNewFile());//文件不存时根据抽象路径创建
    58         System.out.println(file.delete());//删除目录或者文件,如果是文件,则直接删除,如果是目录,空目录则删除返回true,如果不是空目录,返回false
    59         file.deleteOnExit();//强制删除,不管目录下是否为空
    60         
    61         //获取抽象路径下的目录和文件名称或者所有的抽象路径
    62         file.list();//返回抽象路径下所有文件名或者目录名的字符串数组(接收参数FilenameFilter)
    63         file.listFiles();//返回抽象路径下所有文件或者目录的抽象路径File数组(FileFilter或者FilenameFilter)
    64         
    65         file.renameTo(new File("2"));
    66         
    67         //文件系统操作
    68         File[] listRoots = file.listRoots();  //获取系统所有根目录 C:  D:  E:
    69         long totalSpace = file.getTotalSpace();//获取文件所在根目录总容量
    70         long freeSpace = file.getFreeSpace();//获取文件所在磁盘的可用空间大小
    71         long usableSpace = file.getUsableSpace();//获取文件所在磁盘已经使用的空间大小
    72         
    73         
    74         int compareTo = file.compareTo(new File("E:\test\"));//比较两个目录,返回0表示路径相同
    75         boolean equals = file.equals(new File("E:\test\"));//比较两个目录,返回true表示路径相同,否则返回false
    76         
    77         file.toString();//返回抽象路径的字符串路径,调用的getPath()方法
    78         Path path = file.toPath();//抽象路径转成Path对象
    79     }
    80 }
      1 import java.io.BufferedReader;
      2 import java.io.BufferedWriter;
      3 import java.io.File;
      4 import java.io.FileInputStream;
      5 import java.io.FileNotFoundException;
      6 import java.io.FileOutputStream;
      7 import java.io.FileReader;
      8 import java.io.FileWriter;
      9 import java.io.IOException;
     10 import java.io.InputStream;
     11 import java.io.InputStreamReader;
     12 import java.io.OutputStream;
     13 import java.io.OutputStreamWriter;
     14 import java.util.ArrayList;
     15 import java.util.List;
     16 
     17 /**
     18  * @ClassName: FileUtil
     19  * @Description: File工具类
     20  */
     21 public class FileUtil {
     22     
     23     private FileUtil() {}
     24     private static File file = null;
     25     private static List<File> fList = new ArrayList<File>();
     26     private static List<String> sList = new ArrayList<String>();
     27     private static List<byte[]> bList = new ArrayList<byte[]>();
     28     
     29     private static InputStream in = null;
     30     private static OutputStream out = null;
     31     
     32     private static BufferedReader br = null;
     33     private static BufferedWriter bw = null;
     34     
     35     @SuppressWarnings("unused")
     36     private static int num = -1;
     37     private static String str = null;
     38     
     39     /**
     40      * @Title: getFile
     41      * @Description: 根据文件路径,判断该文件是否存在,如果不存在则创建,并返回该file对象
     42      * @param pathName
     43      * @return File  返回类型
     44      * @throws
     45      */
     46     public static File getFile(String pathname) {
     47         file = new File(pathname);
     48         try {
     49             if(!file.exists()) {
     50                 file.createNewFile();
     51             }
     52         } catch (IOException e) {
     53             e.printStackTrace();
     54         }
     55         return file;
     56     }
     57     
     58     /**
     59      * @Title: getAllFile
     60      * @Description: 获取目录下所有的文件,1.传入文件路径,返回该文件的File实例。2.如果传入目录路径,返回目录下所有文件实例
     61      * @param pathname
     62      * @return List<File>
     63      * @throws
     64      */
     65     public static List<File> getAllFile(String pathname) {
     66         file = new File(pathname);
     67         
     68         if(file.isDirectory()) {
     69             File[] files = file.listFiles();
     70             for (int i = 0; i < files.length; i++) {
     71                 if(files[i].isFile()) {//如果是文件
     72                     fList.add(files[i]);
     73                 }else {
     74                     getAllFile(files[i].getPath());
     75                 }
     76             }
     77         }else {
     78             fList.add(file);
     79         }
     80         return fList;
     81     }
     82     
     83     
     84     
     85     
     86     
     87     /**
     88      * @Title: readFileByInputStream
     89      * @Description: 根据文件路径,读取文件内容,并返回所读取的所有内容。字节流读取,每次读取1204个字节
     90      * @param frompathname
     91      * @return List<byte[]>  返回类型
     92      * @throws
     93      */
     94     public static List<byte[]> readFileByInputStream(String frompathname) {
     95         try {
     96             in = new FileInputStream(FileUtil.getFile(frompathname));
     97             byte[] b = new byte[1024];
     98             while((num = in.read(b)) != -1) {
     99                 bList.add(b);
    100             }
    101         } catch (FileNotFoundException e) {
    102             e.printStackTrace();
    103         } catch (IOException e) {
    104             e.printStackTrace();
    105         }finally {
    106             if(in!=null) {
    107                 try {
    108                     in.close();
    109                 } catch (IOException e) {
    110                     e.printStackTrace();
    111                 }
    112             }
    113         }
    114         return bList;
    115     }
    116     
    117     /**
    118      * @Title: readFileByInputStream
    119      * @Description: 根据File对象,读取文件内容,并返回所读取的所有内容。字节流读取,每次读取1204个字节,如果file不是文件,则返回null
    120      * @param frompathname
    121      * @return List<byte[]>  返回类型
    122      * @throws
    123      */
    124     public static List<byte[]> readFileByInputStream(File file) {
    125         try {
    126             if(file!=null && file.isFile()) {
    127                 in = new FileInputStream(file);
    128                 byte[] b = new byte[1024];
    129                 while((num = in.read(b)) != -1) {
    130                     bList.add(b);
    131                 }
    132             }else {
    133                 return null;
    134             }
    135         } catch (FileNotFoundException e) {
    136             e.printStackTrace();
    137         } catch (IOException e) {
    138             e.printStackTrace();
    139         }finally {
    140             if(in!=null) {
    141                 try {
    142                     in.close();
    143                 } catch (IOException e) {
    144                     e.printStackTrace();
    145                 }
    146             }
    147         }
    148         return bList;
    149     }
    150     
    151     
    152     /**
    153      * @Title: readFileByInputStreamReader
    154      * @Description: 根据文件路径,读取全部内容,指定编码,字节转字符然后使用缓冲流
    155      * @param pathname
    156      * @return
    157      * @return List<byte[]> 
    158      * @throws
    159      */
    160     public static List<String> readFileByInputStreamReader(String frompathname,String encoding) {
    161         try {
    162             br = new BufferedReader(new InputStreamReader(new FileInputStream(FileUtil.getFile(frompathname)),encoding));
    163             while((str = br.readLine()) != null) {
    164                 sList.add(str);
    165             }
    166         } catch (FileNotFoundException e) {
    167             e.printStackTrace();
    168         } catch (IOException e) {
    169             e.printStackTrace();
    170         }finally {
    171             if(in!=null) {
    172                 try {
    173                     in.close();
    174                 } catch (IOException e) {
    175                     e.printStackTrace();
    176                 }
    177             }
    178         }
    179         return sList;
    180     }
    181     
    182     /**
    183      * @Title: readFileByInputStreamReader
    184      * @Description: 根据File对象,读取全部内容,指定编码,字节转字符然后使用缓冲流
    185      * @param pathname
    186      * @return
    187      * @return List<byte[]> 
    188      * @throws
    189      */
    190     public static List<String> readFileByInputStreamReader(File file,String encoding) {
    191         try {
    192             if(file!=null && file.isFile()) {
    193                 br = new BufferedReader(new InputStreamReader(new FileInputStream(file),encoding));
    194                 while((str = br.readLine()) != null) {
    195                     sList.add(str);
    196                 }
    197             }else {
    198                 return null;
    199             }
    200         } catch (FileNotFoundException e) {
    201             e.printStackTrace();
    202         } catch (IOException e) {
    203             e.printStackTrace();
    204         }finally {
    205             if(in!=null) {
    206                 try {
    207                     in.close();
    208                 } catch (IOException e) {
    209                     e.printStackTrace();
    210                 }
    211             }
    212         }
    213         return sList;
    214     }
    215     
    216     
    217     /**
    218      * @Title: readFileByBufferedReader
    219      * @Description: 根据文件路径,读取全部内容,字符流加缓冲流
    220      * @param pathname
    221      * @return
    222      * @return List<byte[]> 
    223      * @throws
    224      */
    225     public static List<String> readFileByBufferedReader(String frompathname) {
    226         try {
    227             br = new BufferedReader(new FileReader(FileUtil.getFile(frompathname)));
    228             while((str = br.readLine()) != null) {
    229                 sList.add(str);
    230             }
    231         } catch (FileNotFoundException e) {
    232             e.printStackTrace();
    233         } catch (IOException e) {
    234             e.printStackTrace();
    235         }finally {
    236             if(in!=null) {
    237                 try {
    238                     in.close();
    239                 } catch (IOException e) {
    240                     e.printStackTrace();
    241                 }
    242             }
    243         }
    244         return sList;
    245     }
    246     
    247     /**
    248      * @Title: readFileByBufferedReader
    249      * @Description: 根据File对象,读取全部内容,字符流加缓冲流
    250      * @param pathname
    251      * @return List<byte[]> 
    252      * @throws
    253      */
    254     public static List<String> readFileByBufferedReader(File file) {
    255         try {
    256             if(file!=null && file.isFile()) {
    257                 br = new BufferedReader(new FileReader(file));
    258                 while((str = br.readLine()) != null) {
    259                     sList.add(str);
    260                 }
    261             }
    262         } catch (FileNotFoundException e) {
    263             e.printStackTrace();
    264         } catch (IOException e) {
    265             e.printStackTrace();
    266         }finally {
    267             if(in!=null) {
    268                 try {
    269                     in.close();
    270                 } catch (IOException e) {
    271                     e.printStackTrace();
    272                 }
    273             }
    274         }
    275         return sList;
    276     }
    277     
    278     
    279     
    280     /**
    281      * @Title: writeFileByOutputStream
    282      * @Description: 写内容到文件,字节流
    283      * @param list
    284      * @param topathname
    285      * @return void  返回类型
    286      * @throws
    287      */
    288     public static void writeFileByOutputStream(List<byte[]> list,String topathname) {
    289         try {
    290             out = new FileOutputStream(FileUtil.getFile(topathname));
    291             for (byte[] b : list) {
    292                 out.write(b);
    293             }
    294         } catch (FileNotFoundException e) {
    295             e.printStackTrace();
    296         } catch (IOException e) {
    297             e.printStackTrace();
    298         }finally {
    299             if(out!=null) {
    300                 try {
    301                     out.close();
    302                 } catch (IOException e) {
    303                     e.printStackTrace();
    304                 }
    305             }
    306         }
    307     }
    308     
    309     /**
    310      * @Title: writeFileByOutputStream
    311      * @Description: 将指定内容写入到File,字节流
    312      * @param list
    313      * @param topathname
    314      * @return void  返回类型
    315      * @throws
    316      */
    317     public static void writeFileByOutputStream(List<byte[]> list,File file) {//每次需要循环多次写,需优化
    318         try {
    319             if(file!=null && file.isFile()) {
    320                 out = new FileOutputStream(file);
    321                 for (byte[] b : list) {  
    322                     out.write(b);
    323                 }
    324             }
    325         } catch (FileNotFoundException e) {
    326             e.printStackTrace();
    327         } catch (IOException e) {
    328             e.printStackTrace();
    329         }finally {
    330             if(out!=null) {
    331                 try {
    332                     out.close();
    333                 } catch (IOException e) {
    334                     e.printStackTrace();
    335                 }
    336             }
    337         }
    338     }
    339     
    340     
    341     /**
    342      * @Title: writeFileByBufferWrite
    343      * @Description: 写出内容到文件,不能指定编码,字符流
    344      * @param sList
    345      * @param topathname
    346      * @return void  返回类型
    347      * @throws
    348      */
    349     public static void writeFileByBufferWrite(List<String> sList,String topathname) {
    350         try {
    351             bw = new BufferedWriter(new FileWriter(FileUtil.getFile(topathname)));
    352             for (String str : sList) {
    353                 bw.write(str);
    354             }
    355             bw.flush();//将流中的数据刷新出去
    356         } catch (FileNotFoundException e) {
    357             e.printStackTrace();
    358         } catch (IOException e) {
    359             e.printStackTrace();
    360         }finally {
    361             if(out!=null) {
    362                 try {
    363                     out.close();
    364                 } catch (IOException e) {
    365                     e.printStackTrace();
    366                 }
    367             }
    368         }
    369     }
    370     
    371     /**
    372      * @Title: writeFileByBufferWrite
    373      * @Description: 写出内容到文件,字符流
    374      * @param sList
    375      * @param topathname
    376      * @return void  返回类型
    377      * @throws
    378      */
    379     public static void writeFileByBufferWrite(List<String> sList,File file) {
    380         try {
    381             if(file!=null && file.isFile()) {
    382                 bw = new BufferedWriter(new FileWriter(file));
    383                 for (String str : sList) {
    384                     bw.write(str);
    385                 }
    386                 bw.flush();//将流中的数据刷新出去
    387             }else {
    388                 throw new Exception("写入失败,检查file");
    389             }
    390         } catch (FileNotFoundException e) {
    391             e.printStackTrace();
    392         } catch (IOException e) {
    393             e.printStackTrace();
    394         } catch (Exception e) {
    395             e.printStackTrace();
    396         }finally {
    397             if(out!=null) {
    398                 try {
    399                     out.close();
    400                 } catch (IOException e) {
    401                     e.printStackTrace();
    402                 }
    403             }
    404         }
    405     }
    406     
    407     
    408     /**
    409      * @Title: writeFileByOutputStreamWriter
    410      * @Description: 写出内容到文件,可以指定编码格式,字符流
    411      * @param sList
    412      * @param topathname
    413      * @return void  返回类型
    414      * @throws
    415      */
    416     public static void writeFileByOutputStreamWriter(List<String> sList,String topathname) {
    417         try {
    418             bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(FileUtil.getFile(topathname)),"GBK"));
    419             for (String str : sList) {
    420                 bw.write(str);
    421             }
    422             bw.flush();//将流中的数据刷新出去
    423         } catch (FileNotFoundException e) {
    424             e.printStackTrace();
    425         } catch (IOException e) {
    426             e.printStackTrace();
    427         }finally {
    428             if(out!=null) {
    429                 try {
    430                     out.close();
    431                 } catch (IOException e) {
    432                     e.printStackTrace();
    433                 }
    434             }
    435         }
    436     }
    437     
    438     /**
    439      * @Title: writeFileByOutputStreamWriter
    440      * @Description: 写出内容到文件,指定编码格式,字节转字符,加缓冲流
    441      * @param sList
    442      * @param topathname
    443      * @return void  返回类型
    444      * @throws
    445      */
    446     public static void writeFileByOutputStreamWriter(List<String> sList,File file,String encoding) {
    447         try {
    448             if(file!=null && file.isFile()){
    449                 bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),encoding));
    450                 for (String str : sList) {
    451                     bw.write(str);
    452                 }
    453                 bw.flush();//将流中的数据刷新出去
    454             }else {
    455                 throw new Exception("写入失败,检查file");
    456             }
    457         } catch (FileNotFoundException e) {
    458             e.printStackTrace();
    459         } catch (IOException e) {
    460             e.printStackTrace();
    461         } catch (Exception e) {
    462             e.printStackTrace();
    463         }finally {
    464             if(out!=null) {
    465                 try {
    466                     out.close();
    467                 } catch (IOException e) {
    468                     e.printStackTrace();
    469                 }
    470             }
    471         }
    472     }
    473 }
  • 相关阅读:
    Oracle中有大量的sniped会话
    Error 1130: Host '127.0.0.1' is not allowed to connect to this MySQL server
    汉字转换为拼音以及缩写(javascript)
    高效率随机删除数据(不重复)
    vs2010 舒服背景 优雅字体 配置
    mvc中的ViewData用到webfrom中去
    jquery ajax return值 没有返回 的解决方法
    zShowBox (图片放大展示jquery版 兼容性好)
    动感效果的TAB选项卡 jquery 插件
    loading 加载提示······
  • 原文地址:https://www.cnblogs.com/wang1001/p/9756079.html
Copyright © 2011-2022 走看看