• 35648

    文章

  • 23

    评论

  • 20

    友链

  • 最近新加了很多技术文章,大家多来逛逛吧~~~~
  • 喜欢这个网站的朋友可以加一下QQ群,我们一起交流技术。

工具类 读取本地二进制文件到String字符串中 原

欢迎来到阿八个人博客网站。本 阿八个人博客 网站提供最新的站长新闻,各种互联网资讯。 喜欢本站的朋友可以收藏本站,或者加QQ:我们大家一起来交流技术! URL链接:https://www.abboke.com/jsh/2019/0729/102513.html

挑战A.I.,赢百万奖金......了解更多详情>>>

注意:本工具类就是只能读取本地的<二进制>文件。

import java.io.*;

/**
 * 文件操作工具类
 *
 * @author edison_kwok
 */
public class FileUtils {

    /**
     * 本地文件重命名
     *
     * @param file
     * @param newName
     */
    public static void rename(File file, String newName) {
        if (file.exists()) {
            String absolutePath = file.getAbsolutePath();
            String path = absolutePath.substring(0, absolutePath.lastIndexOf("\\") + 1);
            file.renameTo(new File(path + newName));
        }
    }

    /**
     * 功能:Java读取txt文件的内容
     * 步骤:1:先获得文件句柄
     * 2:获得文件句柄当做是输入一个字节码流,需要对这个输入流进行读取
     * 3:读取到输入流后,需要读取生成字节流
     * 4:一行一行的输出。readline()。
     * 备注:需要考虑的是异常情况
     *
     * @param filePath
     */
    public static String readFile(String filePath) {
        InputStreamReader read = null;
        BufferedReader bufferedReader = null;
        String lineTxt = null;
        try {
            String encoding = "UTF-8";
            File file = new File(filePath);
            //判断文件是否存在
            if (file.isFile() && file.exists()) {
                //考虑到编码格式
                read = new InputStreamReader(new FileInputStream(file), encoding);
                bufferedReader = new BufferedReader(read);
                StringBuilder stringBuilder = new StringBuilder();
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    stringBuilder.append(lineTxt);
                }
                return stringBuilder.toString();
            } else {
                throw new RuntimeException("该文件不存在");
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (read != null) {
                    read.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 输出流导出本地文件
     *
     * @param is
     * @param os
     * @throws Exception
     */
    public static void fileUpload(InputStream is, OutputStream os) throws Exception {
        byte[] b = new byte[2048];
        int length = 0;
        while (true) {
            length = is.read(b);
            if (length < 0) break;
            os.write(b, 0, length);
        }
        is.close();
        os.close();
    }

}

相关文章

暂住......别动,不想说点什么吗?
  • 全部评论(0
    还没有评论,快来抢沙发吧!