java io保存文件内容_javaIO流及键盘输入保存到文件中

流是一组有序的数据序列

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

流按操作数据分为字节流和字符流

0818b9ca8b590ca3270a3433284dd417.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();

}

}

}

}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值