Java操作文件输出为字符串以及字符串输出为文件的方法

作者:DoubleFJ 时间:2022-02-01 19:32:45 

文件输出为字符串示例代码:


/**
 * 读取文件为字符串
 *
 * @return
 */
public static String readString() {
 String str = "";
 File file = new File("C:/Users/wan7/Desktop/表单/粗集料试验/粗集料冲击值试验(T0322-2000).html");
 try {
  FileInputStream in = new FileInputStream(file);
  // size 为字串的长度 ,这里一次性读完
  int size = in.available();
  byte[] buffer = new byte[size];
  in.read(buffer);
  in.close();
  str = new String(buffer, "utf-8");
 } catch (IOException e) {
  return null;
 }
 return str;
}

字符串输出为文件示例代码:


/**
 * 输出到文件
 */
public static void outFile(String s) {
 File file = new File("C:/Users/wan7/Desktop/11111111111.html");
 try (FileOutputStream fop = new FileOutputStream(file)) {
  // if file doesn't exists, then create it
  if (!file.exists()) {
   file.createNewFile();
  }
  // get the content in bytes
  byte[] contentInBytes = s.getBytes();
  fop.write(contentInBytes);
  fop.flush();
  fop.close();
  System.out.println("Done");
 } catch (IOException e) {
  e.printStackTrace();
 }
}

来源:https://blog.csdn.net/ffj0721/article/details/73996576

标签:Java,文件,输出,字符串
0
投稿

猜你喜欢

  • springboot中项目启动时实现初始化方法加载参数

    2023-08-31 06:00:40
  • spring boot如何使用POI读取Excel文件

    2022-09-19 21:26:33
  • 如何用Java Stream写出既高雅又装*的代码

    2022-04-13 23:23:58
  • Java 中很好用的数据结构EnumSet

    2023-12-06 09:37:23
  • 详解Maven私 服Nexus的安装与使用

    2023-11-24 12:34:02
  • Java List集合排序实现方法解析

    2023-01-06 05:40:14
  • SpringBoot系列教程之防重放与操作幂等

    2021-12-07 11:51:12
  • Java中计算时间差的方法

    2023-11-15 10:35:44
  • Scala小程序详解及实例代码

    2023-03-29 12:10:56
  • java9新特性Collection集合类的增强与优化方法示例

    2023-01-29 05:16:57
  • SpringBoot中的main方法注入service

    2021-10-31 15:33:33
  • java fastdfs客户端使用实例代码

    2022-11-19 05:35:59
  • DevExpress之ChartControl实现柱状图演示实例

    2023-05-27 08:45:15
  • C# 4.0 大数的运算--BigInteger的应用详解

    2022-02-02 06:40:05
  • Java获取e.printStackTrace()打印的信息方式

    2022-05-18 05:19:26
  • SpringBoot MongoDB与MongoDB GridFS基本使用

    2023-07-31 06:26:47
  • 通过实例讲解springboot整合WebSocket

    2023-03-07 07:02:03
  • 基于jdk1.8的Java源码详解 Integer

    2023-05-08 11:32:22
  • C#导出Excel的示例详解

    2021-12-03 01:55:51
  • SpringBoot中JPA实现Sort排序的三种方式小结

    2022-02-12 23:35:12
  • asp之家 软件编程 m.aspxhome.com