java打开文件、读取文件、关闭文件是怎么实现?

如题所述

第1个回答  推荐于2019-11-15
刚刚给人写的,工你参考
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){//读到null,返回
break;
}

sb.append(content.trim());
}

bf.close();//关闭文件
return sb.toString();
}
}本回答被网友采纳

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网