//京鸿通信科技//www.kyohoon.com//java文件一行一行读取_java一行一行写入或读取文件
2023-02-09 22:04 花无缺Andyi 阅读(49) 评论(0) 编辑 收藏 举报参考地址:
http://www.cnblogs.com/linjiqin/archive/2011/03/23/1992250.html
java中提供一行一行读取的类是 BufferedReader,其有一个readLine()方法。
java中提供一行一行写入的类是 BufferedWriter,其有一个write方法。 【读取文件】
public void readLineFile(String filename){
try {
FileInputStream in = new FileInputStream(filename);
InputStreamReader inReader = new InputStreamReader(in, "UTF-8");
BufferedReader bufReader = new BufferedReader(inReader);
String line = null;
int i = 1;
while((line = bufReader.readLine()) != null){
System.out.println("第" + i + "行:" + line);
i++;
}
bufReader.close();
inReader.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println("读取" + filename + "出错!");
}
}【写入文件】
public void writeLineFile(String filename, String[] content){
try {
FileOutputStream out = new FileOutputStream(filename);
OutputStreamWriter outWriter = new OutputStreamWriter(out, "UTF-8");
BufferedWriter bufWrite = new BufferedWriter(outWriter);
for (int i = 0; i < content.length; i++) {
bufWrite.write(content[i] + "\r\n");
}
bufWrite.close();
outWriter.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println("读取" + filename + "出错!");
}
}
京鸿通信科技//www.kyohoon.com//