IoStream

/*
流分为字节流和字符流
字节流
InputStream   OutputStream
字符流
Reader    Writer


*/
import java.io.*;

class FileWriterDemo
{
	public static void main(String[] args)
	{
		//创建一个FileWriter对象,该对象一被初始化就必须要明确被操作的文件
/*

		FileWriter fw = null;   //在外面创建引用,在try进行初始化

		try{

		//调用 write方法 ,将字符串写入到流中


			 fw = new FileWriter("demo.txt",true);
			//刷新流对象中的缓冲中的数据, 将数据刷到目的地中
			//传递一个true参数,代表不覆盖已有的文件,并在原有文件末尾续写

			 fw.write("afdf\r\nds");

		    }


		catch(IOException e)
		{
		
			System.out.println(e.toString());

		}
	


		finally
		{
			try
			{
				//关闭资源,但关闭之前会刷新一次内部的缓冲中的数据
				if(fw!=null)    // finally中必须要到fw进行判断
					fw.close();
			}
			catch(IOException e)
			{
		
				System.out.println(e.toString());

			}

		}
	
*/
		
		//创建一个文件读取流对象,和指定名称的文件相关联

		//要保证文件是存在的,否则会发生异常
/*
		FileReader fr = null;
		
		try
		{
			fr = new FileReader("demo.txt");

			int num = 0;

			while((num=fr.read())!=-1)
			{

				System.out.print((char)num);
			}

		}

		catch(IOException e )
		{
			System.out.println(e.toString());

		}

		finally
		{
			try
			{
				if(fr!=null)
					fr.close();

			}

			catch(IOException e)
			{
				System.out.println(e.toString());

			}

		}
*/


/*
第二种方式读取:通过字符数组读取
*/
		
		FileReader fr = null;

		try
		{
		
			fr = new FileReader("demo.txt");
			
			//定义一个字符数组,用于存储读到的字符 
			char[] buf = new char[1024];
			
			//返回的是读取的字符数
			int num = 0;

			while((num = fr.read(buf))!=-1)

			{
				System.out.print("num="+num+"..."+new String(buf,0,num));

			}

		}

		catch(IOException e)
		{
			System.out.println(e.toString());


		}

		finally
		{
			try
			{
				if(fr != null)
					fr.close();


			}

			catch(IOException e)
			{
				System.out.println(e.toString());


			}

		}


	}




}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值