大家好,欢迎来到IT知识分享网。
Java读取文件转String
Java读取文件转String
自己总结的Java读取文件转String的两种方法。
方法一
FileUtils的依赖
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
// 文件的路径
String src = "D:\\VsCode\\11.18\\anputest.js";
File file = new File(src);
String js = FileUtils.readFileToString(file, "utf-8");
方法二
String src = "D:\\VsCode\\11.18\\anputest.js";
File file = new File(src);
FileReader fileReader = new FileReader(file);
BufferedReader br = new BufferedReader(fileReader);
StringBuilder sb = new StringBuilder();
String temp = "";
while ((temp = br.readLine()) != null) {
// 拼接换行符
sb.append(temp + "\n");
}
br.close();
String js = sb.toString();
实例
package com.example.test;
import org.apache.commons.io.FileUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class TestReadFile {
public static void main(String[] args) throws Exception {
test1();
//test2();
}
public static void test1() throws Exception {
String src = "D:\\VsCode\\11.18\\anputest.js";
File file = new File(src);
String text = FileUtils.readFileToString(file, "utf-8");
System.out.println(text);
}
public static void test2() throws Exception {
String src = "D:\\VsCode\\11.18\\anputest.js";
File file = new File(src);
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuilder stringBuilder = new StringBuilder();
String temp = "";
while ((temp = bufferedReader.readLine()) != null) {
stringBuilder.append(temp + "\n");
}
bufferedReader.close();
String text = stringBuilder.toString();
System.out.println(text);
}
}
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/23117.html