用来读取text文本中的数据(分两种方式读取)
1.只要没读完,不断的读取
public static String readFile(File file) {
try {
FileInputStream fileInputStream = new FileInputStream(file);
// 把每次读取的内容写入到内存中,然后从内存中获取
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte [] buffer = new byte [1024];
int len = 0;
// 只要没读完,不断的读取
while ((len=fileInputStream.read(buffer))!=-1)
{
outputStream.write(buffer, 0, len);
}
// 得到内存中写入的所有数据
byte [] data = outputStream.toByteArray();
fileInputStream.close();
return new String(data,"utf-8"); //以GBK(什么编码格式)方式转
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
2.一行一行的读取txt文本中的数据
public static String readFile(File file) {
StringBuilder sb = new StringBuilder();//相当于一个容器,可以进行添加和删除操作
try {
FileInputStream fileInputStream = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fileInputStream,"utf-8");//这里的编码方式需要和自己txt文本的编码方式一样,要不然读出来的数据会是乱码
BufferedReader br = new BufferedReader(isr);
String line="";
//一行一行的读取,当不为空是把值添加到StringBuilder中
while((line=br.readLine())!=null)
{
sb.append(line+"\r\n");
}
br.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sb.toString();
}
## 测试
public static void main(String[] args) {
// TODO Auto-generated method stub
String content =readFile(new File("D:\\aaa.txt"));
System.out.print("content:" + content);
}