<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();
}
}