草庐IT

java读取文件,写入文件

风月歌 2025-05-27 原文

Java 中 IO 流

Java 中 IO 流分为几种?

按照流的流向分,可以分为输入流和输出流;

按照操作单元划分,可以划分为字节流和字符流;

按照流的角色划分为节点流和处理流。

Java Io 流共涉及 40 多个类,这些类看上去很杂乱,但实际上很有规则,而且彼此之间存在非常紧

密的联系, Java I0 流的 40 多个类都是从如下 4 个抽象类基类中派生出来的。

InputStream/Reader: 所有的输入流的基类,前者是字节输入流,后者是字符输入流。

OutputStream/Writer: 所有输出流的基类,前者是字节输出流,后者是字符输出流。

递归读取文件夹下的文件,代码怎么实现

/**
     * 递归读取文件夹下的 所有文件
     *
     * @param testFileDir 文件名或目录名
     */
    private static void testLoopOutAllFileName(String testFileDir) {
        if (testFileDir == null) {
            //因为new File(null)会空指针异常,所以要判断下
            return;
        }
        File[] testFile = new File(testFileDir).listFiles();
        if (testFile == null) {
            return;
        }
        for (File file : testFile) {
            if (file.isFile()) {
                System.out.println(file.getName());
            } else if (file.isDirectory()) {
                System.out.println("-------file-------" + file.getName());
                testLoopOutAllFileName(file.getPath());
            } else {
                System.out.println("文件读入有误!");
            }
        }
    }

文件操作工具类:

package com.fyg.common.util;

import com.fyg.common.constants;
import lombok.extern.slf4j.Slf4j;
import org.apache.tools.tar.TarEntry;
import org.apache.tools.tar.TarInputStream;

import java.io.*;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.util.*;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;


/**
 * 操作文件的辅助类
 *
 * @author liqh
 * @version 1.0
 */
@Slf4j
public class FileUtils extends org.apache.commons.io.FileUtils {

    public static final String B_UNIT = "B";
    public static final String KB_UNIT = "KB";
    public static final String MB_UNIT = "MB";
    public static final String GB_UNIT = "GB";
    public static final DecimalFormat decimalFormat = new DecimalFormat("#.0");

    /**
     * 创建目录
     *
     * @param dir
     * @return
     */
    public static boolean createDirectory(String dir) {
        if (!isExistsDirectory(dir)) {
            File folder = new File(dir);
            return folder.mkdirs();
        }
        return false;
    }


    /**
     * 判断当前目录是否存在
     *
     * @param dir
     * @return true:存在  false:不存在
     */
    public static boolean isExistsDirectory(String dir) {
        File folder = new File(dir);
        if (!folder.exists() && !folder.isDirectory()) {
            return false;
        }
        return true;
    }


    /**
     * 创建新的文件名
     */
    public static String renameToUUID(String fileName) {
        return IDUtils.generateId32() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    /**
     * 创建文件
     *
     * @param fileName
     * @return true:创建成功   false:创建失败
     * @throws IOException
     */
    public static boolean createNewFile(String fileName) throws IOException {
        if (!isExistsFile(fileName)) {
            File file = new File(fileName);
            return file.createNewFile();
        }
        return false;
    }


    /**
     * 判断当前文件是否存在
     *
     * @param fileName
     * @return true:存在  false:不存在
     */
    public static boolean isExistsFile(String fileName) {
        File file = new File(fileName);
        return file.exists();
    }


    /**
     * 获取某个文件夹下的所有文件,只包含文件
     *
     * @param dir
     * @return
     */
    public static List<String> getFileList(String dir) {
        List<String> fileNameList = new ArrayList<>();
        File file = new File(dir);
        File[] tempList = file.listFiles();
        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {
                fileNameList.add(tempList[i].getName());
            }
        }
        return fileNameList;
    }

    /**
     * 获取某个文件夹下的所有文件全路径
     *
     * @param dir
     * @return
     */
    public static List<String> getAllFileAbsolute(String dir) {
        List<String> fileNameList = new ArrayList<>();
        return getAllFileAbsolute(dir, fileNameList);
    }

    /**
     * 获取某个文件夹下的所有文件,包含文件夹和文件
     *
     * @param dir
     * @return
     */
    public static List<String> getAllFileAbsolute(String dir, List<String> fileNameList) {
        File file = new File(dir);
        File[] tempList = file.listFiles();
        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {
                fileNameList.add(tempList[i].toString());
            } else if (tempList[i].isDirectory()) {
                getAllFileAbsolute(tempList[i].getAbsolutePath(), fileNameList);
            }
        }
        return fileNameList;
    }

    /**
     * 获取某个文件夹下的所有文件,包含文件夹和文件
     *
     * @param dir
     * @return
     */
    public static List<String> getAllFileName(String dir, List<String> fileNameList) {
        File file = new File(dir);
        File[] tempList = file.listFiles();
        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {
                fileNameList.add(tempList[i].getName());
            } else if (tempList[i].isDirectory()) {
                getAllFileName(tempList[i].getAbsolutePath(), fileNameList);
            }
        }
        return fileNameList;
    }

    /**
     * 获取某个文件夹下的所有文件,包含文件夹和文件
     *
     * @param dir
     * @return
     */
    public static List<String> getAllFileName(String dir) {
        List<String> fileNameList = new ArrayList<>();
        return getAllFileName(dir, fileNameList);
    }

    /**
     * 删除文件,可以是单个文件或文件夹
     *
     * @param fileName 待删除的文件名
     * @return 文件删除成功返回true, 否则返回false
     */
    public static boolean deleteFileOrDirectory(String fileName) {
        File file = new File(fileName);
        if (!file.exists()) {
            return false;
        } else {
            if (file.isFile()) {
                return deleteFile(fileName);
            } else {
                return deleteDirectory(fileName);
            }
        }
    }

    /**
     * 删除单个文件
     *
     * @param fileName 被删除文件的文件名
     * @return 单个文件删除成功返回true, 否则返回false
     */
    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        if (file.isFile() && file.exists()) {
            file.delete();
            return true;
        } else {
            return false;
        }
    }


    /**
     * 删除目录(文件夹)以及目录下的文件
     *
     * @param dir 被删除目录的文件路径
     * @return 目录删除成功返回true, 否则返回false
     */
    public static boolean deleteDirectory(String dir) {
        //如果dir不以文件分隔符结尾,自动添加文件分隔符   
        if (!dir.endsWith(File.separator)) {
            dir = dir + File.separator;
        }
        File dirFile = new File(dir);
        //如果dir对应的文件不存在,或者不是一个目录,则退出   
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        boolean flag = true;
        //删除文件夹下的所有文件(包括子目录)   
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            //删除子文件   
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag) {
                    break;
                }
            }
            //删除子目录   
            else {
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag) {
                    break;
                }
            }
        }
        if (!flag) {
            return false;
        }
        //删除当前目录
        if (dirFile.delete()) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 用于上传或复制文件
     *
     * @param srcFile 源文件
     * @param tarFile 目标文件
     * @throws IOException
     */
    public static void copyFile(File srcFile, File tarFile) throws IOException {
        InputStream inStream = new FileInputStream(srcFile);
        OutputStream outStream = new FileOutputStream(tarFile);
        byte[] buff = new byte[1024];
        int readed = -1;
        while ((readed = inStream.read(buff)) > 0) {
            outStream.write(buff, 0, readed);
        }
        outStream.flush();
        inStream.close();
        outStream.close();
    }


    /**
     * 文件的移动
     *
     * @param srcFile 源文件
     * @param tarFile 目标文件
     * @return
     */
    public static boolean moveTotherFolders(File srcFile, File tarFile) {

        return srcFile.renameTo(tarFile);
    }


    /**
     * 将文件的byte数组转换成目标文件
     *
     * @param srcByte 源文件数组
     * @param tarFile 目标文件
     * @throws IOException
     */
    public static File convertToFile(byte[] srcByte, File tarFile) throws IOException {
        //将字节转换成文件
        OutputStream outStream = new FileOutputStream(tarFile);
        outStream.write(srcByte);
        outStream.flush();
        outStream.close();

        return tarFile;
    }

    /**
     * 将文件的byte数组转换成目标文件
     *
     * @param inStream 源文件数组
     * @param tarFile  目标文件
     * @throws IOException
     */
    public static File convertToFile(InputStream inStream, File tarFile) throws IOException {
        if (inStream == null) return null;

        //将字节转换成文件
        OutputStream outStream = new FileOutputStream(tarFile);

        byte[] buff = new byte[1024];
        int readed = -1;
        while ((readed = inStream.read(buff)) > 0) {
            outStream.write(buff, 0, readed);
        }
        outStream.flush();
        inStream.close();
        outStream.close();

        return tarFile;
    }


    /**
     * 将文件转换成byte数组的形式
     *
     * @param srcFile 目标文件
     * @return byte数组
     * @throws IOException
     */
    public static byte[] converToByte(File srcFile) throws IOException {
        byte[] content = null;

        //转换成byte数组
        InputStream inStream = new FileInputStream(srcFile);
        if (inStream != null) {
            content = new byte[inStream.available()];
            inStream.read(content);
            inStream.close();
        }

        return content;
    }

    /**
     * 将文件转换成byte数组的形式
     *
     * @param inStream 目标文件
     * @return byte数组
     * @throws IOException
     */
    public static byte[] converToByte(InputStream inStream) throws IOException {
        byte[] content = null;
        //转换成byte数组
        if (inStream != null) {
            content = new byte[inStream.available()];
            inStream.read(content);
            inStream.close();
        }
        return content;
    }


    /**
     * 重命名文件
     *
     * @param fileName
     * @return
     */
    public static File renameFile(String filePath, String fileName) {
        filePath = filePath.endsWith(Constants.System.SLANT) ? filePath : filePath + Constants.System.SLANT;
        String oldFileName = filePath + fileName;
        File oldFile = new File(oldFileName);
        String newFileName = DateUtils.getCurrentTimestamp(DateUtils.DATETIME_17) + fileName;
        String newFilePath = filePath + newFileName;
        File newFile = new File(newFilePath);
        if (oldFile.exists() && oldFile.isFile()) {
            oldFile.renameTo(newFile);
        }
        return newFile;
    }


    /**
     * 重命名文件
     *
     * @param sourFile 源文件
     * @param tarFile  目标文件
     * @return
     */
    public static File renameFile(File sourFile, File tarFile) {
        sourFile.renameTo(tarFile);
        return tarFile;
    }


    /**
     * 多个斜杠转成一个斜杠
     *
     * @param path
     * @return
     */
    public static String transformPath(String path) {
        String regex = "/+";
        String regex1 = "\\+";
        return path.replaceAll(regex, "/").replaceAll(regex1, "/");
    }

    /**
     * 删除超时的文件
     *
     * @param tarFile
     * @param aLong
     */
    public static void deleteTimeoutFiles(File tarFile, Long aLong) {
        File[] files = tarFile.listFiles();
        Arrays.stream(files).forEach(file -> {
            Long ftime = file.lastModified();
            if (ftime < aLong) {
                deleteFile(file.getAbsolutePath());
            }
        });
    }

    /**
     * 将传入的二进制数组,获取文件头部对应的二进制信息
     *
     * @param src 二进制数组
     * @return 二进制信息
     * @throws Exception
     */
    public static String bytesToHexString(byte[] src) throws Exception {
        StringBuilder stringBuilder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }


    /**
     * 根据传入的文件取得对应的文件类型
     *
     * @param file 文件对应的信息
     * @return 文件类型
     */
    public static String[] getFileType(File file) throws Exception {
        return getFileType(getFileContent(file));
    }


    /**
     * 根据传入的文件流取得对应的文件类型
     *
     * @param is 文件流
     * @return 文件类型
     */
    public static String[] getFileType(InputStream is) throws Exception {
        return getFileType(getFileContent(is));
    }

    /**
     * 根据文件字节取得对应的文件类型
     *
     * @param srcByte 文件字节
     * @return 文件类型
     */
    public static String[] getFileType(byte[] srcByte) throws Exception {
        return getFileType(getFileContent(srcByte));
    }

    /**
     * 根据传入的头部二进制信息获取文件类型
     *
     * @param fileContent 头部二进制信息
     * @return 文件类型
     * @throws Exception
     */
    public static String[] getFileType(String fileContent) throws Exception {
        //取得文件头对应的二进制数组
        Map<String, String[]> map = getFileSuffixMap();
        String[] fileType = null;
        //便利文件取得对应的文件类型
        if (fileContent != null) {
            for (String key : map.keySet()) {
                if (fileContent.toLowerCase().startsWith(key.toLowerCase())) {
                    fileType = map.get(key);
                    break;
                }
            }
        }
        return fileType;
    }

    /**
     * 根据传入的文件取得文件头部的二进制信息
     *
     * @param file 文件类型
     * @return 二进制信息
     * @throws Exception
     */
    public static String getFileContent(File file) throws Exception {
        return getFileContent(new FileInputStream(file));
    }

    /**
     * 从流中读出前28位字节,再得到文件头信息
     *
     * @param is InputStream对象
     * @return 文件头2进制数组
     * @throws IOException
     */
    public static String getFileContent(InputStream is) throws Exception {
        byte[] b = new byte[28];
        try {
            //取得28位文件头
            is.read(b, 0, 28);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) is.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return getFileContent(b);
    }

    /**
     * 截取二进制数组的前28位,在获得对应的文件头二进制数组信息
     *
     * @param srcByte 传入的二进制数组
     * @return 文件头二进制数组信息
     * @throws Exception
     */
    private static String getFileContent(byte[] srcByte) throws Exception {
        String content = null;
        if (srcByte != null && srcByte.length > 0) {
            //如果二进制文件的长度大于28位,则截取前28位
            byte[] b = new byte[28];
            if (srcByte.length > 28) System.arraycopy(srcByte, 0, b, 0, 28);
            else b = srcByte;
            //取得后最文件
            content = bytesToHexString(b);
        }
        return content;
    }

    /**
     * 取得文件后缀对应的字符串,前4个组成的文件头
     *
     * @return 文件头对应的后缀
     */
    public static Map<String, String[]> getFileSuffixMap() {
        //设置接收参数对应的MAP
        Map<String, String[]> map = new HashMap<String, String[]>();

        //设置对应的值
        map.put("FFD8FF", new String[]{"JPEG"});
        map.put("89504E47", new String[]{"PNG"});
        map.put("47494638", new String[]{"GIF"});
        map.put("49492A00", new String[]{"TIFF"});
        map.put("424D", new String[]{"BMP"});
        map.put("41433130", new String[]{"DWG"});
        map.put("38425053", new String[]{"PSD"});
        map.put("7B5C727466", new String[]{"RTF"});
        map.put("3C3F786D6C", new String[]{"XML"});
        map.put("68746D6C3E", new String[]{"HTML"});
        map.put("44656C69766572792D646174653A", new String[]{"EML"});
        map.put("CFAD12FEC5FD746F", new String[]{"DBX"});
        map.put("2142444E", new String[]{"PST"});
        map.put("D0CF11E0", new String[]{"XLS", "DOC"});
        map.put("5374616E64617264204A", new String[]{"MDB"});
        map.put("FF575043", new String[]{"WPD"});
        map.put("252150532D41646F6265", new String[]{"EPS"});
        map.put("255044462D312E", new String[]{"PDF"});
        map.put("AC9EBD8F", new String[]{"QDF"});
        map.put("E3828596", new String[]{"PWL"});
        map.put("504B0", new String[]{"XLSX", "ZIP"});
        map.put("52617221", new String[]{"RAR"});
        map.put("57415645", new String[]{"WAV"});
        map.put("41564920", new String[]{"AVI"});
        map.put("2E7261FD", new String[]{"RAM"});
        map.put("2E524D46", new String[]{"RM"});
        map.put("000001BA", new String[]{"MPG"});
        map.put("6D6F6F76", new String[]{"MOV"});
        map.put("3026B2758E66CF11", new String[]{"ASF"});
        map.put("4D546864", new String[]{"MID"});
        map.put("494433", new String[]{"MP3"});
        map.put("61646661647366", new String[]{"TXT"});
        map.put("202f2a2a", new String[]{"TXT"});
        return map;
    }


    /**
     * 解析txt文档
     *
     * @param txtFile txt文件
     * @return
     */
    public static List<List<String>> parseTxt(String txtFile, String separator) {
        if (txtFile == null) {
            return null;
        }
        List<List<String>> data = new ArrayList<List<String>>();
        try {
            BufferedReader buffReader = null;
            FileInputStream fi = new FileInputStream(txtFile);
            String carSet = getTxtFileCharSet(new File(txtFile));
            System.out.println(carSet);
            if ("Unicode".equals(carSet)) {
                buffReader = new BufferedReader(new InputStreamReader(fi, "UTF-16"));
            } else if ("Unicode big endian".equals(carSet)) {
                buffReader = new BufferedReader(new InputStreamReader(fi, "UTF-16LE"));
            } else {
                buffReader = new BufferedReader(new InputStreamReader(fi, "UTF-8"));
            }
            System.out.println(Charset.defaultCharset().name());
            String line = "";
            while (buffReader.ready()) {
                line = buffReader.readLine();
                if (StringUtils.isBlank(line)) continue;
                String[] chars = line.split(separator);
                List<String> innerData = new ArrayList<String>();
                for (String charactor : chars) {
                    if (StringUtils.isNotBlank(charactor)) {
                        if ("UTF-8 + BOM".equals(carSet)) {
                            charactor = new String(charactor.getBytes(Charset.defaultCharset().name()), "UTF-8");
                            charactor = charactor.indexOf("?") == 0 ? charactor.substring(1) : charactor;
                        }
                    }
                    innerData.add(charactor);
                }
                data.add(innerData);
            }
            if (buffReader != null) {
                buffReader.close();
                buffReader = null;
            }
            if (fi != null) {
                fi.close();
                fi = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }


    /**
     * 查看文件编码
     *
     * @param file
     * @return
     */
    public static String getTxtFileCharSet(File file) {
        try {
            return getTxtFileCharSet(new FileInputStream(file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 查看TXT文件编码
     *
     * @param inputStream
     * @return
     */
    public static String getTxtFileCharSet(InputStream inputStream) {
        String carSet = "ANSI";
        try {
            byte[] fileHead = new byte[3];
            inputStream.read(fileHead);
            if (-17 == fileHead[0] && -69 == fileHead[1] && -65 == fileHead[2]) {
                carSet = "UTF-8 + BOM";
            } else if (49 == fileHead[0] && 51 == fileHead[1] && 49 == fileHead[2]) {
                carSet = "UTF-8";
            } else if (-1 == fileHead[0] && -2 == fileHead[1]) {
                carSet = "Unicode";
            } else if (-2 == fileHead[0] && -1 == fileHead[1]) {
                carSet = "Unicode big endian";
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                    inputStream = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return carSet;
    }


    /**
     * 写入Txt
     *
     * @param path
     * @param txt
     * @throws IOException
     */
    public static boolean writeFile(String path, String txt) {
        // 相对路径,如果没有则要建立一个新的path文件
        File file = new File(path);
        try {
            // 创建新文件
            createNewFile(file.getAbsolutePath());
            // 字符缓冲输出流:写东西到该文件
            BufferedWriter out = new BufferedWriter(new FileWriter(file));
            // 写东西:\r\n即为换行
            out.write(txt);
            // 把缓存区内容压入文件
            out.flush();
            // 最后关闭流
            out.close();
            //返回成功
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 描述: 获取格式化的文件大小
     * 格式为带单位保留一位小数
     *
     * @param size
     * @return
     */
    public static String getFormatSize(double size) {
        String fileSizeString = "";
        if (size < 1024) {
            fileSizeString = decimalFormat.format(size) + B_UNIT;
        } else if (size < 1048576) {
            fileSizeString = decimalFormat.format(size / 1024) + KB_UNIT;
        } else if (size < 1073741824) {
            fileSizeString = decimalFormat.format(size / 1048576) + MB_UNIT;
        } else {
            fileSizeString = decimalFormat.format(size / 1073741824) + GB_UNIT;
        }
        return fileSizeString;
    }

    /**
     * 获取文件大小
     *
     * @param size
     * @return
     */
    public static String getFormatSize(long size) {
        return getFormatSize((double) size);
    }

    /**
     * 传文件全路径,解压gz文件到当前文件夹
     *
     * @param fileUrl
     * @return
     */
    public static String unGzFile(String fileUrl) {
        String errMess="";
        GZIPInputStream in = null;
        try {
            in = new GZIPInputStream(new FileInputStream(fileUrl));
        } catch(FileNotFoundException e) {
            log.info("File not found. " + fileUrl);
            errMess=e.getMessage();
        } catch (IOException e) {
            e.printStackTrace();
            errMess=e.getMessage();
        }
        String gzFileNameAndUrl = getGzFileNameAndUrl(fileUrl);

        FileOutputStream out = null;
        try {
            out = new FileOutputStream(gzFileNameAndUrl);
        } catch (FileNotFoundException e) {
            log.info("Could not write to file. " + gzFileNameAndUrl);
            errMess=e.getMessage();
        }
        log.info("文件路径=========" + gzFileNameAndUrl);
        try {
            byte[] buf = new byte[1024];
            int len;
            while((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
            deleteFileOrDirectory(fileUrl);
        } catch (IOException e) {
            e.printStackTrace();
            errMess=e.getMessage();
        }
        return errMess;
    }

    /**
     * 传文件全路径,解压zip文件到当前文件夹
     *
     * @param filePath
     * @return
     */
    public static String unzipFile(String filePath) {
        String errMess="";
        String zipDir = filePath.substring(0,filePath.lastIndexOf("/") + 1);
        String name = "";
        try {
            BufferedOutputStream dest = null;
            BufferedInputStream is = null;
            ZipEntry entry;
            ZipFile zipfile = new ZipFile(filePath, Charset.forName("GBK"));

            Enumeration dir = zipfile.entries();
            while (dir.hasMoreElements()){
                entry = (ZipEntry) dir.nextElement();

                if( entry.isDirectory()){
                    name = entry.getName();
                    name = name.substring(0, name.length() - 1);
                    File fileObject = new File(zipDir + name);
                    fileObject.mkdir();
                }
            }

            Enumeration e = zipfile.entries();
            while (e.hasMoreElements()) {
                entry = (ZipEntry) e.nextElement();
                if( entry.isDirectory()){
                    continue;
                }else{
                    is = new BufferedInputStream(zipfile.getInputStream(entry));
                    int count;
                    byte[] dataByte = new byte[1024];
                    FileOutputStream fos = new FileOutputStream(zipDir+entry.getName());
                    dest = new BufferedOutputStream(fos, 1024);
                    while ((count = is.read(dataByte, 0, 1024)) != -1) {
                        dest.write(dataByte, 0, count);
                    }
                    dest.flush();
                    dest.close();
                    is.close();
                }
            }

            deleteFileOrDirectory(filePath);
        } catch (Exception e) {
            e.printStackTrace();
            errMess=e.getMessage();
        }

        return errMess;
    }

    /**
     * 传路径,找出当前路径下所有子目录以及文件
     *
     * @param
     * @return
     */
    public static List<String> findUnzipAllFile(File filePath,List<String> filePaths) {

        File[] files = filePath.listFiles();
        if(files == null){
            return filePaths;
        }
        for(File f:files){
            if(f.isDirectory()){
                filePaths.add(f.getPath());
                findUnzipAllFile(f,filePaths);
            }else{
                filePaths.add(f.getPath());
            }
        }
        return filePaths;
    }

    /**
     * 截取文件后缀
     *
     * @param
     * @return
     */
    public static String checkFile(String filePaths) {
        String hzhwjm = "";
        String houZui = "";
        int i =filePaths.lastIndexOf("/");
        if (i > 0 &&  i < filePaths.length() - 1) {
            hzhwjm = filePaths.substring(i + 1);
        }
        int j =hzhwjm.lastIndexOf(".");
        if (j > 0 &&  j < hzhwjm.length() - 1) {
            houZui = hzhwjm.substring( j+ 1);
        }
        if(houZui.equals("gz")||houZui.equals("GZ")){
            if(j>3){
                if(hzhwjm.substring(j - 3).equals("tar.gz")||hzhwjm.substring(j - 3).equals("TAR.GZ")){
                    houZui=hzhwjm.substring(j - 3);
                }
            }
        }
        return houZui;
    }

    public static String getGzFileNameAndUrl(String f) {
        String fname = "";
        int i = f.lastIndexOf('.');

        if (i > 0 &&  i < f.length() - 1) {
            fname = f.substring(0,i);
        }


        return fname;
    }
    /**
     * 压缩文件通过文件全路径截取文件名
     *
     * @param
     * @return
     */
    public static String getFileNameByAllUrl(String fileAllUrl) {
        String fName = "";
        int i = fileAllUrl.lastIndexOf('/');

        if (i > 0 &&  i < fileAllUrl.length() - 1) {
            fName = fileAllUrl.substring(i+1);
        }
        return fName;

    }
    /**
     * 压缩文件通过文件全路径截取文件路径
     *
     * @param
     * @return
     */
    public static String getFileUrlByAllUrl(String fileAllUrl) {
        String fUrl = "";
        int i = fileAllUrl.lastIndexOf('/');

        if (i > 0 &&  i < fileAllUrl.length() - 1) {
            fUrl = fileAllUrl.substring(0,i+1);
        }
        return fUrl;
    }

    /**
     * 解压tar.gz 传文件全路径
     * @param filePath
     *
     */
    public static String unTarGz(String filePath) throws IOException{
        String outputDir = filePath.substring(0,filePath.lastIndexOf("/") + 1);
        String errMess="";
        File file = new File(filePath);
        TarInputStream tarIn = null;
        try{
            tarIn = new TarInputStream(new GZIPInputStream(
                    new BufferedInputStream(new FileInputStream(file))),
                    1024 * 2);

            createDirectory(outputDir,null);//创建输出目录

            TarEntry entry = null;
            while( (entry = tarIn.getNextEntry()) != null ){

                if(entry.isDirectory()){//是目录
                    entry.getName();
                    createDirectory(outputDir,entry.getName());//创建空目录
                }else{//是文件
                    File tmpFile = new File(outputDir + "/" + entry.getName());
                    createDirectory(tmpFile.getParent() + "/",null);//创建输出目录
                    OutputStream out = null;
                    try{
                        out = new FileOutputStream(tmpFile);
                        int length = 0;

                        byte[] b = new byte[2048];

                        while((length = tarIn.read(b)) != -1){
                            out.write(b, 0, length);
                        }

                    }catch(IOException ex){
                        errMess=ex.getMessage();
                        throw ex;
                    }finally{
                        if(out!=null)
                            out.close();
                    }
                }
            }
        }catch(IOException ex){
            errMess=ex.getMessage();
            throw new IOException("解压归档文件出现异常",ex);
        } finally{
            try{
                if(tarIn != null){
                    tarIn.close();
                }
            }catch(IOException ex){
                errMess=ex.getMessage();
                throw new IOException("关闭tarFile出现异常",ex);
            }
        }
        deleteFileOrDirectory(filePath);
        return errMess;
    }

    /**
     * 构建目录
     * @param outputDir
     * @param subDir
     */
    public static void createDirectory(String outputDir,String subDir){
        File file = new File(outputDir);
        if(!(subDir == null || subDir.trim().equals(""))){//子目录不为空
            file = new File(outputDir + "/" + subDir);
        }
        if(!file.exists()){
            if(!file.getParentFile().exists())
                file.getParentFile().mkdirs();
            file.mkdirs();
        }
    }

    /**
     * 解析txt删除第一行字段
     * @param fileName
     *
     */
    public static void removeFirstLine(String fileName) throws IOException {

        RandomAccessFile raf = new RandomAccessFile(fileName, "rw");


        long writePosition = raf.getFilePointer();

        raf.readLine();



        long readPosition = raf.getFilePointer();

        byte[] buff = new byte[1024];

        int n;

        while (-1 != (n = raf.read(buff))) {

            raf.seek(writePosition);

            raf.write(buff, 0, n);

            readPosition += n;

            writePosition += n;

            raf.seek(readPosition);

        }

        raf.setLength(writePosition);

        raf.close();

    }



}
package com.fyg.common.constants;

public final class Constants {

    /**
     * code码
     */
    public static final class Code {
        /**
         * 成功 success
         */
        public static final String SUCCESS = "00";
        /**
         * 参数不正确
         */
        public static final String PARAM_INVALID = "01";

        /**
         * 文件下载
         */
        public static final String FILE_DOWNLOAD_FILE = "96";

        /**
         * 上传文件超过限制
         */
        public static final String FILE_UPLOAD_FILE_MAX = "97";
        /**
         * 文件上传
         */
        public static final String FILE_UPLOAD = "98";
        /**
         * 系统异常
         */
        public static final String UNKNOW_ERROR = "99";

        /**
         * 未登录不通过
         */
        public static final String NO_LOGIN = "02";

        /**
         * 数据重复
         */
        public static final String DATA_REPEAT = "03";
    }

    /**
     * code 码提示信息
     */
    public static final class Message {
        /**
         * 成功 success(00)
         */
        public static final String SUCCESS = "success";
        /**
         * 上传文件超过限制
         */
        public static final String FILE_UPLOAD_FILE_MAX = "upload file is failed, %s";

        /**
         * 下载文件错误
         */
        public static final String FILE_DOWNLOAD_FILE = "download file is failed, %s";

        /**
         * 文件上传错误(98)
         */
        public static final String FILE_UPLOAD = "The file cannot be empty, please contact the administrator!";
        /**
         * 错误信息(99)
         */
        public static final String UNKNOW_ERROR = "system problem, please contact administrator!";

        /**
         * 未登录提示信息(02)
         */
        public static final String NO_LOGIN = "未登录或登录已超时,请登录!!!";


        /**
         * 数据重复
         */
        public static final String DATA_REPEAT = "该数据已存在,请勿重复提交!";

    }

    /**
     * 系统常量
     */
    public static final class System {
        /**
         * /
         */
        public static final String SLANT = "/";
        /**
         * \
         */
        public static final String UNSLANT = "\\";
        /**
         * ,
         */
        public static final String COMMA = ",";
        /**
         * 空字符串("")empty
         */
        public static final String EMPTY = "";
        /**
         * " "
         */
        public static final String SPACE = " ";
        /**
         * .
         */
        public static final String SPOT = ".";
        /**
         * :
         */
        public static final String COLON = ":";
        /**
         * (string *)
         */
        public static final String ASTERISK = "*";
        /**
         * (string ?)
         */
        public static final String ASK = "?";
        /**
         * -
         */
        public static final String TRANSVERSE = "-";
        /**
         * ;
         */
        public static final String SEMICOLON = ";";
        /**
         * |
         */
        public static final String STRAIGHT = "|";
        /**
         * _
         */
        public static final String UNDERLINE = "_";
        /**
         * UTF-8
         */
        public static final String UTF8 = "UTF-8";
        /**
         * GBK
         */
        public static final String GBK = "GBK";
        /**
         * ISO-8859-1
         */
        public static final String ISO88591 = "ISO-8859-1";
        /**
         * url 地址参数连接符(&)
         */
        public static final String AND = "&";
        /**
         * 等于(=)
         */
        public static final String EQUAL = "=";
        /**
         * 艾特(@)
         */
        public static final String AT = "@";
    }

    public static final class ID {
        /**
         * 用户ID前缀
         */
        public static final String ID_USER = "USER";
        /**
         * 角色ID前缀
         */
        public static final String ID_ROLE = "ROLE";
        /**
         * 菜单ID前缀
         */
        public static final String ID_MENU = "MENU";
        /**
         * 附件ID前缀
         */
        public static final String ID_FILE = "FILE";

    }

    public static final class Web {
        /**
         * 登录类型(随机码)
         */
        public static final String LOGIN_TYPE_CODE = "code";
        /**
         * 登录类型(密码)
         */
        public static final String LOGIN_TYPE_PASSWORD = "password";
        /**
         * 电话
         */
        public static final String PHONE = "phone";
        /**
         * 邮箱
         */
        public static final String EMAIL = "email";

        /**
         * web端
         */
        private static final String PROJECT = "web";

        /**
         * 在线用户
         */
        public static final String ONLINE_USER = "online.user";

        /**
         * 令牌
         */
        public static final String TOKEN = "TOKEN";

        /**
         * 用户登录session key
         */
        public static final String SESSION_USER = PROJECT + ".manager.session.user";

    }


    /**
     * redis key
     */
    public static final class Redis {
        /**
         * 所有配置项
         */
        public static final String CONFIG_ALL = Web.PROJECT + ":db:config:";
        /**
         * 检测是否登录的例外地址配置
         */
        public static final String REQUEST_CONFIG = CONFIG_ALL + "page.login.notcheck";

        /**
         * 用户
         */
        public static final String USER_USER = Web.PROJECT + ":login:user:user:";
        /**
         * 用户、角色
         */
        public static final String USER_ROLE = Web.PROJECT + ":login:user:role:";

        /**
         * 角色
         */
        public static final String ROLE_ROLE = Web.PROJECT + ":login:role:role:";

        /**
         * 角色、菜单
         */
        public static final String ROLE_MENU = Web.PROJECT + ":login:role:menu:";

        /**
         * 菜单
         */
        public static final String MENU_MENU = Web.PROJECT + ":login:menu:menu:";

        /**
         * 组织
         */
        public static final String ORGAN_ORGAN = Web.PROJECT + ":login:organ:organ:";

        /**
         * 组织、角色
         */
        public static final String ORGAN_ROLE = Web.PROJECT + ":login:organ:role:";

        /**
         * 令牌
         */
        public static final String TOKEN = Web.PROJECT + ":token:";

    }

    public static final class OpsLogType {

        /**
         * 添加
         */
        public static final String ADD = "ADD";

        /**
         * 修改
         */
        public static final String UPDATE = "UPDATE";

        /**
         * 删除
         */
        public static final String DELETE = "DELETE";

        /**
         * 查询
         */
        public static final String SELECT = "SELECT";

        /**
         * 设置
         */
        public static final String SET = "SET";

        /**
         * 重置
         */
        public static final String RESET = "RESET";

        /**
         * 停用
         */
        public static final String STOP = "STOP";

        /**
         * 上传
         */
        public static final String UPLOAD = "UPLOAD";

        /**
         * 下载
         */
        public static final String DOWNLOAD = "DOWNLOAD";

        /**
         * 登陆
         */
        public static final String LOGIN = "LOGIN";

        /**
         * 退出
         */
        public static final String LOGINOUT = "LOGINOUT";
    }

}

在 Java 中,File 类是 java.io 包中唯一代表磁盘文件本身的对象,也就是说,如果希望在程序中操作文件和目录,则都可以通过 File 类来完成。File 类定义了一些方法来操作文件,如新建、删除、重命名文件和目录等。

File 类不能访问文件内容本身,如果需要访问文件内容本身,则需要使用输入/输出流。

File 类提供了如下三种形式构造方法。

  1. File(String path):如果 path 是实际存在的路径,则该 File 对象表示的是目录;如果 path 是文名,则该 File 对象表示的是文件。

  1. File(String path, String name):path 是路径名,name 是文件名。

  1. File(File dir, String name):dir 是路径对象,name 是文件名。

Java IO流是既可以从中读取,也可以写入到其中的数据流。正如这个系列教程之前提到过的,流通常会与数据源、数据流向目的地相关联,比如文件、网络等等。

流和数组不一样,不能通过索引读写数据。在流中,你也不能像数组那样前后移动读取数据,除非使用RandomAccessFile 处理文件。流仅仅只是一个连续的数据流。

某些类似PushbackInputStream 流的实现允许你将数据重新推回到流中,以便重新读取。然而你只能把有限的数据推回流中,并且你不能像操作数组那样随意读取数据。流中的数据只能够顺序访问。

Java IO流通常是基于字节或者基于字符的。字节流通常以“stream”命名,比如InputStream和OutputStream。除了DataInputStream 和DataOutputStream 还能够读写int, long, float和double类型的值以外,其他流在一个操作时间内只能读取或者写入一个原始字节。

字符流通常以“Reader”或者“Writer”命名。字符流能够读写字符(比如Latin1或者Unicode字符)。可以浏览Java Readers and Writers获取更多关于字符流输入输出的信息。

InputStream

java.io.InputStream类是所有Java IO输入流的基类。如果你正在开发一个从流中读取数据的组件,请尝试用InputStream替代任何它的子类(比如FileInputStream)进行开发。这么做能够让你的代码兼容任何类型而非某种确定类型的输入流。

然而仅仅依靠InputStream并不总是可行。如果你需要将读过的数据推回到流中,你必须使用PushbackInputStream,这意味着你的流变量只能是这个类型,否则在代码中就不能调用PushbackInputStream的unread()方法。

通常使用输入流中的read()方法读取数据。read()方法返回一个整数,代表了读取到的字节的内容(译者注:0 ~ 255)。当达到流末尾没有更多数据可以读取的时候,read()方法返回-1。

有关java读取文件,写入文件的更多相关文章

  1. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  2. ruby - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  3. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  4. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  5. ruby - 将差异补丁应用于字符串/文件 - 2

    对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl

  6. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  7. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  8. Ruby 写入和读取对象到文件 - 2

    好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信

  9. ruby - 如何使用 Ruby aws/s3 Gem 生成安全 URL 以从 s3 下载文件 - 2

    我正在编写一个小脚本来定位aws存储桶中的特定文件,并创建一个临时验证的url以发送给同事。(理想情况下,这将创建类似于在控制台上右键单击存储桶中的文件并复制链接地址的结果)。我研究过回形针,它似乎不符合这个标准,但我可能只是不知道它的全部功能。我尝试了以下方法:defauthenticated_url(file_name,bucket)AWS::S3::S3Object.url_for(file_name,bucket,:secure=>true,:expires=>20*60)end产生这种类型的结果:...-1.amazonaws.com/file_path/file.zip.A

  10. ruby - rspec 需要 .rspec 文件中的 spec_helper - 2

    我注意到像bundler这样的项目在每个specfile中执行requirespec_helper我还注意到rspec使用选项--require,它允许您在引导rspec时要求一个文件。您还可以将其添加到.rspec文件中,因此只要您运行不带参数的rspec就会添加它。使用上述方法有什么缺点可以解释为什么像bundler这样的项目选择在每个规范文件中都需要spec_helper吗? 最佳答案 我不在Bundler上工作,所以我不能直接谈论他们的做法。并非所有项目都checkin.rspec文件。原因是这个文件,通常按照当前的惯例,只

随机推荐