java中的输入输出流--简单练习

1.fileinputsteam and fileoutputstream

try {
			FileOutputStream output = new FileOutputStream(file);
			byte[] b = new byte[10];
			for (int i = 0; i < b.length; ++i)
				b[i] = (byte) i;

			output.write(b);
			output.close();

			FileInputStream input = new FileInputStream(file);
			List<Byte> c = new ArrayList<Byte>();
			int len = 0;
			while ((len = input.read()) != -1) {
				Byte by = Byte.valueOf((byte) len);
				c.add(by);
			}
			for (Byte d : c)
				System.out.println(d);

			input.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

2.bufferedinputstream and bufferedoutputstream

try {
			BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(file));
			String str = "I can make it";
			char[] c = new char[20];
			c = str.toCharArray();
			for (char ch : c)
				output.write(ch);

			output.close();
			BufferedInputStream input = new BufferedInputStream(new FileInputStream(file));
			List<Character> L = new ArrayList<Character>();
			int len = 0;
			while ((len = input.read()) != -1) {
				Character C = Character.valueOf((char) len);
				L.add(C);
			}
			for (Character d : L)
				System.out.println(d);
			System.err.println(L.size());
			input.close();
		} catch (FileNotFoundException e) {
			System.err.println("file out found");
			e.printStackTrace();
		} catch (IOException e) {
			System.err.println("写入文件异常");
			e.printStackTrace();
		}

3.system.in

System.out.println("请输入字符");
		char ch;
		try {
			while ((ch = (char) System.in.read()) != 'x') {
				System.out.println("* " + ch); // 读入的时候如果敲回车相当于输入两个字符 \r和\n
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

4.datainputstream and dataoutputstream

try {
			DataOutputStream output = new DataOutputStream(new FileOutputStream(file));
			for (int i = 0; i < 10; ++i)
				output.writeInt(i);

			output.close();
			DataInputStream input = new DataInputStream(new FileInputStream(file));
			List<Object> list = new ArrayList<Object>();
			int len = 0;
			while (true) {
				try {
					len = input.readInt();
					list.add(len);
				} catch (EOFException e) {
					break;	//datainputstream 流以EOFException 结束标志
				}
			}
			for (Object obj : list)
				System.out.println(obj.toString());
			input.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值