字节输出流与输入流
字节输出流与字节输入流
字节流是原生的操作,是由字节组成。在进行网络数据传输时,所用的数据类型就是字节。
字节的输出流
OutputStream实现了程序输出内容到文件的处理,由于OutputStream是一个抽象类,所以不能实例化对象,要想实例化对象必须使用子类进行实例化。例如:OutputStream output=new FileOutputStream(file);
下面还文件输出的一个例子:建议文件目录不要选择桌面,选择一个自己容易找到的一个文件目录。
import java.io.*;
public class Test {
public static void main(String[] args) {
String directory="E:"+ File.separator+"code"+File.separator+"test.txt";//定义文件目录
File file=new File(directory);//定义文件
if(!file.getParentFile().exists()){//此时如果父目录不存在,就创建多级父目录;
file.getParentFile().mkdirs();//如果父目录不存在,用mkdir()创建,就不能创建成功。mkdir()只能创建当前文件
}
OutputStream output = null;//OutputStream是一个抽象类,需要通过子类进行实例化。
try {
output = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String str="youaremysunshine";
try {
output.write(str.getBytes());//将内容变为字节数组输出
} catch (IOException e) {
e.printStackTrace();
}
try {
output.close();//关闭输出
} catch (IOException e) {
e.printStackTrace();
}
}
}
如果想要进行文件追加,就选择FileOutputStream(File file,boolean append)接收追加子类。
字节输入流
InputStream是实现了在程序中读取文件中的内容。同样的,InputSream也是一个抽象类,如果要进行实例化,同样也需要子类,如果要对文件进行处理,则使用FileOutputStream类。
下面是实现文件信息的读取
import java.io.*;
public class Test{
public static void main(String[] args) {
String directory="E:"+ File.separator+"code"+File.separator+"test.txt";//定义文件目录
File file=new File(directory);//定义文件
if(file.exists()){//需要保证文件存在
InputStream input= null;//实例化子类
try {
input = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte[] data=new byte[1024];//每次读取的最大数量
int len= 0;
try {
len = input.read(data);//将数据读取到数组
} catch (IOException e) {
e.printStackTrace();
}
String result=new String(data,0,len);//将字节数组转为String
System.out.println("读取的内容:"+result);
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}