Java File类功能扩展

在Java中,File类无法提供:删除文件指定行,获得文件指定行,复制文件的某一行到指定文件,文件倒序,以及匹配文件中的关键信息等操作。而这些操作往往又是我们工作中需要用到的,今天写出来供大家分享。

package util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;


public class DoWithFile {

    /**
     * @param inPutFilePath
     * @param OutputFilePath
     * @param startLine
     * @param endLine
     * @describe 复制文件中的指定行数到指定的文件中
     * @return
     */
    public static boolean copyFileByLineRang(String inPutFilePath, String OutputFilePath, int startLine, int endLine){
        if(inPutFilePath == null || inPutFilePath.trim().equals("") || OutputFilePath == null || OutputFilePath.trim().equals("") || startLine < 0 || endLine < 0 || startLine > endLine){
            return false;
        }
        String stringTemp = null;
        try {
            ArrayList<String> arrayList = new ArrayList<String>();
            File inPutFile = new File(inPutFilePath);
            File outPutFile = new File(OutputFilePath);
            if(!inPutFile.exists()){
                return false;
            }
            if(!outPutFile.exists()){
                outPutFile.getParentFile().mkdirs();
            }
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(inPutFile),"UTF-8"));
            while((stringTemp = bufferedReader.readLine()) != null){
                arrayList.add(stringTemp);
            }
            bufferedReader.close();
            if(arrayList.size() > 0){
                //不想覆盖原有的信息,那么就加一个true,表示后续追加
//              PrintWriter printWriter = new PrintWriter(new FileOutputStream(outPutFile,true));
                PrintWriter printWriter = new PrintWriter(new FileOutputStream(outPutFile));
                endLine = Math.min(arrayList.size(), endLine + 1);
                if(startLine > endLine){
                    return false;
                }
                for(int linCount = startLine; linCount < endLine; linCount++){
                    printWriter.println(arrayList.get(linCount));
                    printWriter.flush();
                }
                printWriter.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * @param inPutFilePath
     * @param OutputFilePath
     * @param startLine
     * @param endLine
     * @describe 根据关键字来获取到对应的信息,并且输出到指定文件
     * @return
     */
    public static boolean outPutFileByContains(String inPutFilePath, String OutputFilePath, String containStrtemp){
        if(inPutFilePath == null || inPutFilePath.trim().equals("") || OutputFilePath == null || OutputFilePath.trim().equals("") || containStrtemp == null || containStrtemp.equals("")){
            return false;
        }
        String stringTemp = null;
        try {
            ArrayList<String> arrayList = new ArrayList<String>();
            File inPutFile = new File(inPutFilePath);
            File outPutFile = new File(OutputFilePath);
            if(!inPutFile.exists()){
                return false;
            }
            if(!outPutFile.exists()){
                outPutFile.getParentFile().mkdirs();
            }
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(inPutFile),"UTF-8"));
            while((stringTemp = bufferedReader.readLine()) != null){
                arrayList.add(stringTemp);
            }
            bufferedReader.close();
            if(arrayList.size() > 0){
                boolean ifFind = false;
                PrintWriter printWriter = new PrintWriter(new FileOutputStream(outPutFile));
                for(int linCount = 0; linCount < arrayList.size(); linCount++){
                    stringTemp = arrayList.get(linCount);
                    if(stringTemp.contains(containStrtemp)){
                        ifFind = true;
                        System.out.println("Line: " + (linCount<10?"0"+linCount:linCount)  + "       contant is:  \"" + stringTemp + "\"");
                        printWriter.println(arrayList.get(linCount));
                        printWriter.flush();
                    }
                }
                printWriter.close();
                if(!ifFind){
                    System.out.println("没有找到相应的信息");
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * @param filePath
     * @param index
     * @describe 获取文件中指定行的内容
     * @return
     */
    public static String getOneLine(String filePath, int index){
        if(filePath == null || filePath.trim().equals("") || index < 0){
            return null;
        }
        String stringTemp = null;
        try {
            ArrayList<String> arrayList = new ArrayList<String>();
            File file = new File(filePath);
            if(!file.exists()){
                return null;
            }
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
            while((stringTemp = bufferedReader.readLine()) != null){
                arrayList.add(stringTemp);
            }
            bufferedReader.close();
            if(arrayList.size() > index){
                return arrayList.get(index);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param filePath
     * @param index
     * @describe 删除文件中指定行的内容
     * @return
     */
    public static String deleteOneLineByLinecount(String filePath, int index){
        if(filePath == null || filePath.trim().equals("")){
            return null;
        }
        String stringTemp = null;
        try {
            ArrayList<String> arrayList = new ArrayList<String>();
            File file = new File(filePath);
            if(!file.exists()){
                return null;
            }
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
            while((stringTemp = bufferedReader.readLine()) != null){
                arrayList.add(stringTemp);
            }
            bufferedReader.close();
            PrintWriter printWriter = new PrintWriter(file);
            if(arrayList.size() > index){
                stringTemp = arrayList.get(index);
                arrayList.remove(index);
            }
            if(arrayList.size() > 0){
                for(String str : arrayList){
                    printWriter.println(str);
                    printWriter.flush();
                }
            }
            printWriter.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringTemp;
    }

    /**
     * @param filePath
     * @describe 倒序文件
     * @return
     */
    public static boolean reverseFile(String filePath){
        if(filePath == null || filePath.trim().equals("")){
            return false;
        }
        String stringTemp = null;
        try {
            ArrayList<String> arrayList = new ArrayList<String>();
            File file = new File(filePath);
            if(!file.exists()){
                return false;
            }
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
            while((stringTemp = bufferedReader.readLine()) != null){
                arrayList.add(stringTemp);
            }
            bufferedReader.close();
            PrintWriter printWriter = new PrintWriter(file);
            if(arrayList.size() > 0){
                for(int i = arrayList.size()-1; i >= 0; i--){
                    printWriter.println(arrayList.get(i));
                    printWriter.flush();
                }
            }
            printWriter.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }


    /**
     * @param fileinput
     * @param fileoutput
     * @throws IOException
     * @describe 以字节流的形式将一个文件复制到指定的地方,这种方式比较适合于那些应用程序的复制以及用网络socket形式传输文件
     *           因为安装程序需要一个字节都准确无误的传送过去,因而需要使用字节流,同时注意缓冲数组的字节数读取长度,
     *           原则:写进去多少字节,就读取多少字节。
     */
    public static void copyFile(File fileinput, File fileoutput) throws IOException{
        fileinput = new File("D:/LiufuKin/AccountNum.txt");
        fileoutput = new File("D:/LiufuKin/test/AccountNum.txt");
        if(!fileinput.exists()){
            System.out.println("你所选择的文件不存在");
            return ;
        }
        //写信息如缓存去数组
        if(!fileoutput.exists()){
            fileoutput.getParentFile().mkdirs();
        }
        FileInputStream fileInputStream = new FileInputStream(fileinput);
        byte[] bt = new byte[1024000];
        FileOutputStream fileOutputStream = new FileOutputStream(fileoutput);
        int lengthTemp = 0;
        while((lengthTemp = fileInputStream.read(bt)) >0){
            fileOutputStream.write(bt,0,lengthTemp); //这一步很重要,写入缓冲区多少,就拿出来多少,否则会使得文件和原来的不一样。
            fileOutputStream.flush();
        }
        fileInputStream.close();
        fileOutputStream.close();
    }

    /**
     * @param file
     * @throws IOException
     * @describe 以字符流的形式,一行一行的读取文件,这种方式适用于对文件进行分析,匹配的场景
     */
    public static void readFile(File file) throws IOException{
        if(!file.exists()){
            System.out.println("你选择的文件不存在");
            return;
        }
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            System.out.println(str);
        }
    }

    /**
     * @param file
     * @param length
     * @describe 显示文件夹之下所有的文件名
     */
    public static void showAllFile(File file,int length){
        String string = "----------------------------------------";
        ArrayList<File> arrayList = new ArrayList<File>();
        if(!file.exists()){
            System.out.println("文件不存在");
            return ;
        }
        if(file.isDirectory()){
            if(length==0){
                System.out.println("文件夹:" + file.getName());
            }else{
                System.out.println(string.substring(0,length) + file.getParentFile().getName() + "~~子文件夹:" + file.getName());
            }
            File[] files = file.listFiles();
            if(files ==null || files.length ==0){
                return;
            }
            for(File subFile : files){
                if(subFile.isDirectory()){
                    arrayList.add(subFile);
                }else{
                    System.out.println(string.substring(0,length+4) + subFile.getName());
                }
            }
            System.out.println();

            if(arrayList.size() >0){
                for (File subFile:arrayList) {
                    System.out.println();
                    showAllFile(subFile,length+4);
                }
            }
        }else{
            System.out.println(string.substring(0,length)+file.getName());
        }
    }
}

注意:如果不想覆盖原有的文件内容,则需要在创建输出流的时候,在outputFileStream 中指定为“true”。比如:
//不想覆盖原有的信息,那么就加一个true,表示后续追加
PrintWriter printWriter = new PrintWriter(new FileOutputStream(outPutFile,true));

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值