如何用Java读取一个txt文件,并将文件内容保存到String类型的变量中?求Java代码!

如题所述

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();
}
}
温馨提示:内容为网友见解,仅供参考
第1个回答  2018-01-05
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();
}
}
第2个回答  2011-02-26
Reader reader = null;
BufferedReader br = null;
try {

reader = new FileReader("txt文件地址");
br = new BufferedReader(reader);
StringBuffer sb = new StringBuffer();
String data = null;
while ((data = br.readLine()) != null) {
sb.appand(data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
相似回答