java——字节流

<span style="color:#cc0000">字节流</span>

前提:程序中所有的数据都是以流的方式进行传输或保存的,字节流主要操作type类型的数据,以type数组为准
输入流:将数据流从本地加载到程序中     文件→java   InputStream类
输出流:程序将数据流写入到本地文件中  java→文件  OutputStream类

输出流:
public class FileOutputStream extends OutputStream
前提 FileOutputStream引入new File(name),且文件不存在不会创建
常用方法
#实例化
public FileOutputStream(String name)   #创建文件输出流对象
public FileOutputStream(String name,boolean append)  #创建文件输出流对象,且可自动追加数据
public FileOutputStream(File file)  #创建文件输出流对象
public FileOutputStream(File file,boolean append)  ##创建文件输出流对象,且可自动追加数据
#写数据流到本地文件中
private native void write(int b,boolean append)
private native void writeBytes(byte b[],int off,int len,boolean append)

private native void write(byte b[])

#关闭数据流
public void close()

注:写代码时注意上转

 


输入流
public class FileIutputStream extends IutputStream
前提 FileIutputStream引入new File(name)
常用方法
#实例化 创建文件输入流
public FileIutputStream(String name)   #创建文件输出流对象
public FileIutputStream(File file)  #创建文件输出流对象
#读取文件内容
public int read()
public native int readBytes(byte b[],int off,int len)
public int read(byte b[])
public int read(byte b[],int off,int length)
#关闭数据流

 

 

 

public void close()

注:写代码时注意上转

总结:IO操作步骤
1)使用File类打开一个文件
2)通过字节流指定输出的位置
3)进行读写操作

4)关闭输入/输出

输入流

 
package com.youceedu.test.iostream;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;

public class TestInputStream {
   public static void main(String[] args) throws IOException {// TODO Auto-generated method 
       stubString path="D:\\test.txt";
       //实例化一个文件对象
       File f = new File(path);
       //实例化一个输入流对象
       FileInputStream intput = new FileInputStream(f);
       //操作读
       byte[] b = new byte[256];
       //创建一个数组可存放1024个byte类型的值//
       int fileContentLen = -1;
       while(intput.read(b)!=-1) {
           System.out.println(new String(b)); //调用String(byte byte[]) 
           System.out.println(String.valueOf(b));//相当于输出 b.toString()
           System.out.println(Arrays.toString(b)); //输出字符长度
    }
    intput.close();
  }
}

 

package com.youceedu.test.iostream;

import java.io.File;
import java.io.FileOutputStream;

public class TestOutputStream {

	public static void main(String[] args) throws Exception{
		// TODO Auto-generated method stub
		String path="D:\\test.txt";
		//实例化文件的一个对象
		File f = new File(path);
		//实例化输出流的对象
		FileOutputStream out = new FileOutputStream(f,false);
		//操作写
		String str="ajfhhsjdJDJAJDJAJ";
		byte b[]=str.getBytes();
		for(byte tmp:b) {
			System.out.print(tmp+"\t");
		}
		out.write(b);
		out.close();
	}

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值