怎样读取本地二进制文件到String字符串中

发布时间:2021-10-19 16:00:39 作者:柒染
来源:亿速云 阅读:113

本篇文章为大家展示了怎样读取本地二进制文件到String字符串中,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

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

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();
    }

}

上述内容就是怎样读取本地二进制文件到String字符串中,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. java通过url读取远程数据并保持到本地
  2. java如何读取二进制文件

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

string

上一篇:后端服务器如何自动解压zip压缩包

下一篇:servlet基础是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》