• java 文件操作


    一、获取文件列表

      方法一:DirFilter类实现了FilenameFilter接口,需要重写FilenamFilter中的accept方法。

     1 /**
     2  * java文件操作  获取文件列表
     3  * 2016/6/15
     4  */
     5 package fileStream;
     6 
     7 import java.io.File;
     8 import java.io.FilenameFilter;
     9 import java.util.regex.*;
    10 import java.util.*;
    11 
    12 public class DirList {
    13     public static void main(String[] args){
    14         File path = new File("G:");
    15         String[] list;
    16         if(args.length == 0){
    17             list = path.list();
    18         }else{
    19             list = path.list(new DirFilter(args[0]));
    20         }
    21         Arrays.sort(list, String.CASE_INSENSITIVE_ORDER);
    22         for(String dirItem:list){
    23             System.out.println(dirItem);
    24         }
    25     }
    26 }
    27 
    28 class DirFilter implements FilenameFilter {
    29     private Pattern pattern;
    30     public DirFilter(String regex){
    31         pattern = Pattern.compile(regex);
    32     }
    33     @Override
    34     public boolean accept(File dir, String name) {
    35         return pattern.matcher(name).matches();
    36     }
    37 }
    View Code

      方法二:使用匿名内部类

     1 /**
     2  * 获取文件列表方法2  匿名内部类
     3  * 2016/6/15
     4  */
     5 package fileStream;
     6 
     7 import java.io.*;
     8 import java.util.*;
     9 import java.util.regex.*;
    10 
    11 
    12 public class DirList2 {
    13     public static FilenameFilter filter(final String regex){
    14         return new FilenameFilter(){
    15             private Pattern pattern = Pattern.compile(regex);
    16             @Override
    17             public boolean accept(File dir, String name){
    18                 return pattern.matcher(name).matches();
    19             }
    20         };
    21     }
    22     public static void main(String[] args){
    23         File path = new File("G:");
    24         String[] list;
    25         if(args.length == 0){
    26             list = path.list();
    27         }else{
    28             list = path.list(new DirFilter(args[0]));
    29         }
    30         Arrays.sort(list, String.CASE_INSENSITIVE_ORDER);
    31         for(String dirItem:list){
    32             System.out.println(dirItem);
    33         }
    34     }
    35 
    36 }
    View Code

      方法二改进:

     1 /**
     2  * Thinking in Java
     3  * 获取文件列表  方法二改进
     4  * 2016/6/15
     5  */
     6 package fileStream;
     7 
     8 import java.util.*;
     9 import java.util.regex.*;
    10 import java.io.*;
    11 
    12 public class DirList3 {
    13     public static void main(final String[] args){
    14         File path = new File("G:");
    15         String[] list;
    16         if(args.length == 0){
    17             list = path.list();
    18         }else{
    19             list = path.list(new FilenameFilter() {
    20                 private Pattern pattern = Pattern.compile(args[0]);
    21                 public boolean accept(File dir, String name) {
    22                     return pattern.matcher(name).matches();
    23                 }
    24             });
    25         }
    26             Arrays.sort(list, String.CASE_INSENSITIVE_ORDER);
    27             for(String dirItem : list){
    28                 System.out.println(dirItem);
    29             }
    30     }
    31 }
    View Code

    二、文本文件的读写

     1 /**
     2  * 文本文件的读写
     3  * 2016/6/15
     4  */
     5 package fileStream;
     6 
     7 import java.io.BufferedReader;
     8 import java.io.FileOutputStream;
     9 import java.io.FileReader;
    10 import java.io.IOException;
    11 import java.util.Scanner;
    12 
    13 
    14 public class FileStream {
    15     public static void main(String[] args) throws IOException{
    16         //写入文件
    17         FileOutputStream outFile = new FileOutputStream("E:/1.txt",true);
    18         StringBuffer outText = new StringBuffer();
    19         String str = null;
    20         Scanner input = new Scanner(System.in);
    21         byte[] writeByte = null;
    22         while(true){
    23             str = input.nextLine();
    24             outText.append(str);
    25             if(str.equals("quit")) break;
    26         }
    27         
    28         writeByte = (outText+"").getBytes();
    29         outFile.write(writeByte);
    30         outFile.close();
    31         
    32         //读取文件
    33         BufferedReader  reader = new BufferedReader(new FileReader("E:/1.txt"));
    34         String text = null;    
    35         while((text = reader.readLine()) != null){
    36             System.out.println(text);
    37         }
    38         reader.close();
    39     }
    40 }
    View Code

    三、二进制文件的读取

     1 //此处只提供方法,主函数请自行书写
     2 public static byte[] read(File bfile) throws IOException {
     3         BufferedInputStream bf = new BufferedInputStream(new FileInputStream(bfile));
     4         try {
     5             byte[] data = new byte[bf.available()];
     6             bf.read(data);
     7             return data;
     8         } catch (Exception e) {
     9             // TODO: handle exception
    10         }finally{
    11             bf.close();
    12         }
    13         return null;
    14     }
    View Code

    四、进程控制

      传入操作系统的命令,后台运行后获取输出,并打印出来。

     1 /**
     2  * Thinking in Java
     3  * 进程控制  运行操作系统命令,发送输出到控制台
     4  * 2016/6/16
     5  */
     6 package fileStream;
     7 import java.io.*;
     8 
     9 public class OSExecute {
    10     public static void command(String command) {
    11         boolean err = false;
    12         try {
    13             //创建一个新的Process实例
    14             Process process = new ProcessBuilder(command.split(" ")).start();
    15             BufferedReader results = new BufferedReader(new InputStreamReader(process.getInputStream()));
    16             String s;
    17             while((s = results.readLine()) != null){
    18                 System.out.println(s);
    19             }
    20             //获取错误信息
    21             BufferedReader errors = new BufferedReader(
    22                     new InputStreamReader(process.getErrorStream()));
    23             while ((s = errors.readLine()) != null) {
    24                 System.err.println(s);
    25                 err = true;
    26             }
    27         }catch(Exception e) {
    28             if(!command.startsWith("CMD /C")){
    29                 command("CMD /C" + command);
    30             }else{
    31                 throw new RuntimeException(e);
    32             }
    33             if(err){
    34 //                throw new OSExecuteException("Errors executing " + command);
    35             }
    36         }
    37     }
    38     public static void main(String[] args){
    39         String path="F:\java\work_1\Stream\bin\fileStream/";  
    40         String commandw="javap "+path+"OSExecute.class";  
    41         OSExecute.command(commandw);    //传入CMD命令
    42     }
    43 }
    View Code

    五、新I/O

    JDK1.4中的java.nio.*包引入了行动JavaI/O类库,可以提高读取速度。

     1 /**
     2  * Thinking in Java P552
     3  * java 新I/O
     4  * 2016/6/16
     5  */
     6 package fileStream;
     7 
     8 import java.io.FileInputStream;
     9 import java.io.FileNotFoundException;
    10 import java.io.FileOutputStream;
    11 import java.io.IOException;
    12 import java.io.RandomAccessFile;
    13 import java.nio.ByteBuffer;
    14 import java.nio.channels.FileChannel;
    15 
    16 public class GetChannel {
    17     private static final int BSIZE = 1024;
    18     public static void main(String[] args){
    19         try {
    20             //写入文件
    21             FileChannel  fc = new FileOutputStream("1.txt").getChannel();
    22             fc.write(ByteBuffer.wrap("hello world".getBytes()));
    23             fc.close();
    24             //在文件尾添加内容
    25             fc = new RandomAccessFile("1.txt", "rw").getChannel();
    26             fc.position(fc.size());        //移动到文件末尾
    27             fc.write(ByteBuffer.wrap("More Hello World".getBytes()));
    28             fc.close();
    29             //读取文件
    30             fc = new FileInputStream("1.txt").getChannel();
    31             ByteBuffer buff = ByteBuffer.allocate(BSIZE);
    32             fc.read(buff);
    33             buff.flip();
    34             while(buff.hasRemaining()){
    35                 System.out.print((char)buff.get());
    36             }
    37         } catch (FileNotFoundException e) {
    38             // TODO Auto-generated catch block
    39             e.printStackTrace();
    40         } catch (IOException e) {
    41             // TODO Auto-generated catch block
    42             e.printStackTrace();
    43         }
    44     }
    45     
    46 
    47 }
    View Code

     六、文件复制

     1 /**
     2  * Thinking in Java
     3  * 文件复制
     4  * 2016/6/16
     5  */
     6 package fileStream;
     7 
     8 import java.io.File;
     9 import java.io.FileInputStream;
    10 import java.io.FileOutputStream;
    11 import java.nio.ByteBuffer;
    12 import java.nio.channels.FileChannel;
    13 
    14 public class ChannelCopy {
    15     private static final int BSIZE = 1024;
    16     public static void main(String[] args) throws Exception {
    17         File sourceFile = new File("1.txt");    //源文件
    18         File DestFile = new File("1_copy.txt");    //要复制的目标文件
    19 
    20         FileChannel in = new FileInputStream(sourceFile).getChannel();
    21         FileChannel out = new FileOutputStream(DestFile).getChannel();
    22         ByteBuffer buffer = ByteBuffer.allocate(BSIZE);
    23         while (in.read(buffer) != -1) {
    24             buffer.flip();
    25             out.write(buffer);
    26             buffer.clear();
    27         }
    28         in.close();
    29         out.close();
    30     }
    31 
    32 }
    View Code

    七、文件内容替换

     1 /**
     2  * 替换某文件夹下所有以.txt 结尾的文件中的"java"字符串,替换为"****"
     3  */
     4 package com;
     5 
     6 import java.io.BufferedReader;
     7 import java.io.File;
     8 import java.io.FileInputStream;
     9 import java.io.FileNotFoundException;
    10 import java.io.FileOutputStream;
    11 import java.io.IOException;
    12 import java.io.InputStreamReader;
    13 import java.io.OutputStreamWriter;
    14 import java.io.UnsupportedEncodingException;
    15 import java.util.ArrayList;
    16 import java.util.List;
    17 
    18 public class ReadAllFile {
    19 
    20     // 读取一个文件夹下所有文件及子文件夹下的所有文件
    21     public static void readAllFile(String filePath) {
    22         File f = new File(filePath);
    23         File[] files = f.listFiles(); // 得到f文件夹下面的所有文件。
    24         List<File> list = new ArrayList<File>();
    25         for (File file : files) {
    26             if (file.isDirectory()) {
    27                 // 如何当前路劲是文件夹,则循环读取这个文件夹下的所有文件
    28                 readAllFile(file.getAbsolutePath());
    29             } else {
    30                 list.add(file);
    31             }
    32         }
    33         for (File file : files) {
    34             String fileName = file.getName();
    35             if (fileName.endsWith("txt")) {
    36                 // 替换所有的java字符串
    37                 replace(file);
    38             }
    39         }
    40     }
    41 
    42     //替换
    43     private static void replace(File file) {
    44         InputStreamReader isr;
    45         OutputStreamWriter osw;
    46         try {
    47             isr = new InputStreamReader(new FileInputStream(file), "UTF-8");
    48             BufferedReader br = new BufferedReader(isr);
    49             String str = "";
    50             StringBuffer index = new StringBuffer();
    51             while ((str = br.readLine()) != null) {
    52                 System.out.println(str);
    53                 index.append(str.replaceAll("java", "****") + '
    ');
    54             }
    55             osw = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
    56             osw.write(index.toString());
    57             osw.flush();
    58             br.close();
    59         } catch (UnsupportedEncodingException e) {
    60             e.printStackTrace();
    61         } catch (FileNotFoundException e) {
    62             e.printStackTrace();
    63         } catch (IOException e) {
    64             e.printStackTrace();
    65         }
    66 
    67     }
    68 
    69     public static void main(String[] args) {
    70         String filePath = "F:\Test";
    71         readAllFile(filePath);
    72     }
    73 }
    View Code
  • 相关阅读:
    基于分布式思想下的RPC解决方案--笔记
    前端对页面展示修改出现的问题------行内块元素(标签)、行内元素(标签)、块元素(标签)的区别
    POI读取带有图片(图片有的是合并单元格的)的商品列表Excel
    Springboot 默认加载文件(可直接访问、不可直接访问)是出现的问题
    for循环快还是递归快
    try catch finally 中遇到的return问题(经典)
    为什么阿里巴巴禁止在 foreach 循环里进行元素的 remove/add 操作
    数据结构Java实现03----单向链表的插入和删除
    匿名内部类详解(粗略)
    非法字符: 'ufeff' idea下的解决方案
  • 原文地址:https://www.cnblogs.com/snail-lb/p/5588574.html
Copyright © 2020-2023  润新知