Java按行讀取文本文件和寫文件

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




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章