javaIO流及键盘输入保存到文件中

本文详细介绍了Java中IO流的概念及其分类,并通过一个具体的键盘输入到文件的实例,展示了如何使用不同类型的流进行数据读写操作。文章还涉及了字节流与字符流的区别,输入流与输出流的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

流是一组有序的数据序列

源。。。。流:都有可能是文件,网络,压缩包,

流按操作数据分为字节流和字符流   153715_chvu_3536141.png

字节流按照一个字节8位来读(8位都是01010101类型的)

字符流按照一个字符来读

流按流向分为输入流和输出流

例子:键盘输入然后存到硬盘的文件里面(多行输入)

package suibian;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class Test {

	public static void main(String[] args) {
		String targetPath = "d:/keyBoard/input.txt";
		File targetFile = new File(targetPath);//准备文件接收他
		
		String msg = null;
		InputStream is = null;
		InputStreamReader  isr = null;
		BufferedReader br = null;
		FileOutputStream fos = null;
		OutputStreamWriter osw = null;
		BufferedWriter bw = null;
		
		
		try {//控制台得到GBK字符,他会自动帮你转字节
			is = System.in; //流引用尽量在代码块中执行
			isr = new InputStreamReader(is,"UTF-8");////然后你读字符按照GBK的格式把自己读入的字节转成GBK编码的字符
			br = new BufferedReader(isr);
			/*FileOutputStream(File file, boolean append) 
			Creates a file output stream to write to the file represented by the specified File object*/
			fos = new FileOutputStream(targetFile, true);
			//输出的时候把字节按照utf-8的格式输出来,因为utf-8的格式包含GBk,utf-8更加灵活
			osw = new OutputStreamWriter(fos, "UTF-8");
			bw = new BufferedWriter(osw);
			
			while (true) {
				msg = br.readLine();
				System.out.println(msg);
				if ("over".equals(msg)) {
					break;
				}
				bw.write(msg, 0, msg.length());
				bw.newLine();
				bw.flush();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != is) {
					is.close();
				}
				
				if (null != isr) {
					isr.close();
				}
				
				if (null != br) {
					br.close();
				}
				
				if (null != fos) {
					fos.close();
				}
				
				if (null != osw) {
					osw.close();
				}
				
				if (null != bw) {
					bw.close();
				}
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}
		
		
		
		
	}

}

优秀博客:http://blog.youkuaiyun.com/jierong01/article/details/53394161?locationNum=1&fps=1

http://blog.youkuaiyun.com/zhangliangzi/article/details/51226652

转载于:https://my.oschina.net/u/3536141/blog/1483870

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值