Java按行读取文本文件和写文件

来源:互联网 发布:手机淘宝咋改手机号 编辑:程序博客网 时间:2024/05/17 08:50

有时候我们需要按行读取文本文件,可以用BufferedReader

import java.io.*;public class Test{public static void main(String[] args) throws Exception{BufferedReader br = null;try{br = new BufferedReader(new FileReader("test.txt"));String s = null;while((s = br.readLine()) != null){System.out.println(s);}}catch(IOException ioe){ioe.printStackTrace();}finally{if(br != null){    br.close();}}}}



将字符串内容写入到文件中,可以用PrintStream类

import java.io.*;public class Test{public static void main(String[] args)throws Exception{PrintStream ps = null;try{ps = new PrintStream("test.txt");ps.println("I love Java");ps.flush();}catch(IOException ioe){ioe.printStackTrace();}finally{if(ps != null){ps.close();}}}}