如何用Java读取一个txt文件,并将文件内容保存到String类型的变量中?
1个回答
展开全部
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
public static void main(String[] args) throws IOException {
String fileContent = readFileContent("");
System.out.println(fileContent);
}
//参数string为你的文件名
private static String readFileContent(String fileName) throws IOException {
File file = new File(fileName);
BufferedReader bf = new BufferedReader(new FileReader(file));
String content = "";
StringBuilder sb = new StringBuilder();
while(content != null){
content = bf.readLine();
if(content == null){
break;
}
sb.append(content.trim());
}
bf.close();
return sb.toString();
}
}
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
public static void main(String[] args) throws IOException {
String fileContent = readFileContent("");
System.out.println(fileContent);
}
//参数string为你的文件名
private static String readFileContent(String fileName) throws IOException {
File file = new File(fileName);
BufferedReader bf = new BufferedReader(new FileReader(file));
String content = "";
StringBuilder sb = new StringBuilder();
while(content != null){
content = bf.readLine();
if(content == null){
break;
}
sb.append(content.trim());
}
bf.close();
return sb.toString();
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询