声明:来自尚学党马老师的教程代码 节点流类型(一根管直接插到下面的类型上,下面的管道指的是线程和线和之间的通讯) 类型 字符流 字节流 File FileReader
掌握内存操作流的使用
此时操作的时候应该以内存为操作点。
利用此类完成一些功能
ByteArrayInputStream:
public class ByteArrayInputStream extends InputStream 构造方法:
public Byte ArrayInputStream(byte[] buf)
接收一个byte数组,实际上内存的输入就是在构造方法上将数据传入到内存之中。//读文件 BufferedReaderBufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("fileUrl"))));String tempStr = ""
ByteArrayOutputStream:
输出就是从内存中写出数据。
public void write(int b)
利用它完成一个大小写字母转换的程序
import java.io.* ;
public class ByteArrayDemo01{
public static void main(String args[]){
String str = "HELLOWORLD" ;// 定义一个字符串,全部由大写字母组成
ByteArrayInputStream bis = null ;// 内存输入流
ByteArrayOutputStream bos = null ;// 内存输出流
bis = new ByteArrayInputStream(str.getBytes()) ;// 向内存中输出内容
bos = new ByteArrayOutputStream() ;// 准备从内存ByteArrayInputStream中读取内容
int temp = 0 ;
while((temp=bis.read())!=-1){
char c = (char) temp ;// 读取的数字变为字符
bos.write(Character.toLowerCase(c)) ;// 将字符变为小写
}
// 所有的数据就全部都在ByteArrayOutputStream中
String newStr = bos.toString() ;// 取出内容
try{
bis.close() ;
bos.close() ;
}catch(IOException e){
e.printStackTrace() ;
}
System.out.println(newStr) ;
}
};如果要想把一个字符变为小写,则可以通过包装类: Character
总结:
1、内存操作流的操作对象一定是以内存为准,不要以程序为准
2、实际此时可以通过向上转型关系为OutputStream 或 InputStream 实例化
import java.io.* ;
public class ByteArrayDemo01{
public static void main(String args[])throws Exception{
String str = "HELLOWORLD" ;// 定义一个字符串,全部由大写字母组成
InputStream bis = null ;// 内存输入流
OutputStream bos = null ;// 内存输出流
bis = new ByteArrayInputStream(str.getBytes()) ;// 向内存中输出内容
bos = new ByteArrayOutputStream() ;// 准备从内存ByteArrayInputStream中读取内容
int temp = 0 ;
while((temp=bis.read())!=-1){
char c = (char) temp ;// 读取的数字变为字符
bos.write(Character.toLowerCase(c)) ;// 将字符变为小写
}
// 所有的数据就全部都在ByteArrayOutputStream中
String newStr = bos.toString() ;// 取出内容
try{
bis.close() ;
bos.close() ;
}catch(IOException e){
e.printStackTrace() ;
}
System.out.println(newStr) ;
}
};实际上,以上的操作可以很好的体现对象的多态性,通过实例化其子类的不同,完成的功能也不同,也就是相当于输出位置也就不同,如果是文件,则使用FileXxx,如果是内存,则使用ByteArrayXxx.
内存输出流在日后的JAVA的开发中也是经常要使用到的,所以一定要重点掌握。
java IO操作 (读写、追加、删除、移动、复制等) 一、多种方式读文件内容。 1、按字节读取文件内容 2、按字符读取文件内容 3、按行读取文件内容 4、随机读取文件