有时候我们需要按行读取文本文件,可以用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();
}
}
}
}