字节流之向文件中写入字符串并读出字符串

1、InputStream(输入字节流)

InputStream是一个定义了Java流式字节输入模式的抽象类,该类的所有方法在出错时都会引发一个IOExceptin异常。

          方法                          描述 

      int available()             返回当前可读的输入字节数

      void close()               关闭输入流。关闭之后若再读取则会产生IOException    

     void mark(int numBytes)   再输入流当前带点放置一个标志。

     boolean markSupported()  如果调用的流支持mark()/reset()就返回true

     int read()

     int read(byte buffer[])

     int read(byte buffer[],int offset,int numBytes)

     void reset()

     long skip(long numBytes)


2、OutputStream

     void close()

     void flush()

      void write(int b)

     void write(byte buffer[])

     void write(byte buffer[],int offset,int numBytes)


3、FileInputStream (文件输入流)

     FileInputStream(String filepath)

     FileInputStream(File fileObj)

4、FileOutputStream (文件输入流)

     FileOutputStream(String filePaht)

     FileOutputStream(File fileObj)

     FileOutputStream(String filePath,boolean append)


package IO;

import java.io.*;

public class StreamDemo {
	public static void main(String[] args) {
		//创立一个文件
		File f = new File("E:\\Java\\iodemo.txt"); 
		
		//将数据写入文件中
		OutputStream out = null;
		try {
			out = new FileOutputStream(f);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		String str = "Hello World!!";
		byte b[] = str.getBytes();
		
		try {
			out.write(b);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//读文件
		InputStream in = null;
		try {
			in = new FileInputStream(f);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		byte b1[] = new byte[1024];
		int i = 0;
		try {
			i = in.read(b1);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
       
		System.out.println(new String(b1,0,i));
	}
}

      








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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值