java流对象

java流对象

定义

IO,简单来说,就是输入输出,包括IO设备和IO接口。

从发生IO的位置来说,分为系统IO和网络IO;从不同实现方式来分,有BIO,NIO以及AIO。

输入流

实现子类

  • 直接实现
    • FileInputStream
    • ByteArrayInputStream
  • 间接实现
    • FilterInputStream
      • BufferedInputStream
  • 字符流
    • Reader

这里FilterInputStream采用装饰器模式,扩展流对象的特性。

装饰器模式通过委托来做,实现委托类的部分或者全部方法,不想覆盖原行为的直接由委托类处理。

装饰器模式伪实现

class InputStreamDelegate {
	InputStream in;
	
	//注入委托类
	public InputStreamDelegate(InputStream in){this.in = in}
	
	@OVERRIDE
	public synchronized int read(){
		in.read();
	}
	
	@OVERRIDE
	public synchronized int read(byte[] b, int off, int len) {
		in.read(b,off,len);
	}
	
	。。。
}

这里没有改变InputStram的任何行为,所有方法都交给委托类处理,可根据实际情况改变InputStream的行为。

生活场景:去4s店买车,4s店作为生产商的代理(或者说生产商将汽车委托给4s店买),你选好了车以后,它往往会给你推销内饰和豪华音响或者其它一些定制改造等等。 这里 车 就可以理解类的原始行为和属性,4s店可以对部分行为做装饰,然后卖给消费者。

FileInputStream

  • read(): 读取流中的第一个字符的Ascii码

  • read(byte[] byte):读取流中的字符填充byte数组,直到byte数组满了,就不再填充

  • read(byte[] byte, int offset, int len):读取流中的字符填充byte数组,指定偏移值和读取长度

  • avaiable(): 流中有效字符长度

  • skip():跳过指定长度字符

    /**
     * @Auther: allen
     * @Date: 2020-09-13 17:03
     * @Description:
     */
    @RunWith(SpringJUnit4ClassRunner.class)
    public class FileInputStramTest {
    
        private FileInputStream in;
    
        @Before
        public void init() throws FileNotFoundException {
        	//初始化读取流,文件里内容:i am allen
            in = new FileInputStream(new File("D:\\test.txt"));
        }
    
        @Test
        @DisplayName("返回流中首字符的ascii码值")
        public void testRead() throws IOException {
            int num = in.read();
    		// i的ascii为105
            assertEquals(105, num);
        }
    
        @Test
        public void testReadWithArgs() throws IOException {
            byte[] bytes = new byte[1024];
           	//读取流中字符到bytes,由于流比较小,所有流中内容都填充到了bytes数组
            int n = in.read(bytes);
            assertEquals("i am allen", new String(bytes,0,n, "utf-8"));
        }
    
        @Test
        public void  testskip() throws IOException {
            in.skip(2);
            //a的ascii是97
            assertEquals(97, in.read());
        }
    
        @Test
        public void testAvaiable() throws IOException {
        
        	//流的有效字符长度是10
            assertEquals(10, in.available());
        }
    
    
        @After
        public void destroy() throws IOException {
            in.close();
        }
    }
    
    

ByteArrayInputStram

与FileInputStream不同的是, 通过byte数组初始化流对象

@RunWith(SpringJUnit4ClassRunner.class)
public class ByteArrayInputStramTest {

    private ByteArrayInputStream in;

    @Before
    public void init(){
        //通过byte数组初始化流,内容:i am allen
        byte[] inputs = new byte[]{105,32,97,109,32,97,108,108,101,110};
        in = new ByteArrayInputStream(inputs);
    }

    @Test
    public void testByteArrayInputStream() throws IOException {
        byte[] bytes = new byte[1024];
        int len = in.read(bytes);

        assertEquals("i am allen",new String(bytes,0,len));
    }
}

格式化

public class StringFormatDemo {

    public static void main(String[] args) {
        System.out.printf("Hello,%s\n", "World");


        System.out.print(String.format("Hello,%s\n","World"));
    }
}

printf方法等同于String的format方法,格式化字符串。此外java里还有一系列formatter结尾的方法,都是格式化的,例如:DateFormatter,DatetimeFormatter以及NumberFormatter.

扫描器

public class ScannerDemo {

    public static void main(String[] args) {
        StringReader reader = new StringReader("A,B,C");

        Scanner scanner = new Scanner(reader);
        //指定分隔符
        scanner.useDelimiter(",");

        while ( scanner.hasNext() ){
            System.out.println(scanner.next());
        }

    }
}

扫描流对象,并按指定分隔符分割,默认分隔符是\n

输入流对象

public class CommandLineDemo {

    public static void main(String[] args) throws IOException {
        System.out.println("请输入任意内容结束...");
        //从控制台读取流
        System.in.read();
    }
}

输出流对象

public class DataOutputStreamDemo {

    public static void main(String[] args) throws IOException {
        //将对象输出到控制台
        DataOutputStream outputStream = new DataOutputStream(System.out);
		
		//打印字符
        outputStream.writeByte(65);
        outputStream.writeByte(97);

        outputStream.writeUTF("Hello,world");
        outputStream.flush();
        outputStream.close();
    }
}

对象序列化

public class ObjectStreamDemo {

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        List<String> strings = new ArrayList<>(Arrays.asList("A,B,C"));

        File file = new File("strings.ser");

        //对象序列化
        try(ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(file))){
            objectOutputStream.writeObject(strings);
            objectOutputStream.flush();
        }

        //对象反序列化
        try (ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(file))){
            List<String> copyStrings = (List<String>) inputStream.readObject();
            System.out.println(copyStrings);
        }

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值