java io stream

本文详细介绍了二进制文件和文本文件的输入输出操作。包括使用FileInputStream、FileOutputStream、BufferedReader等进行文件读写的方法,以及如何正确关闭流确保文件修改生效。

binary file input

  • FileInputStream
  • BufferedInputStream
InputStream in = new BufferedInputStream (new FileInputStream (fileName));
byte[] data = new byte[1024];
int length = in.read(data);

read() returns length of binary number it gets and save the number to data.
when it reads nothing, read() returns -1.

binary file output

  • FileOutputStream
  • BufferedInputStream
OutputStream out = new BufferedOutputStream (new FileOutputStream (fileName));
out.writer (data, 0, length);

writer() gets numbers of data from 0 to length, and saves them to file.

binary file io example

InputStream in = new BufferedInputStream (new FileInputStream (inFileName));
OutputStream out = new BufferedOutputStream (new FileOutputStream (outFileName));
byte[] data = new byte[1024];
int length = -1;

while ((length = in.read (data)) != -1) {
  out.writer (data, 0, length);
}

in.close();
out.close();

it should be noticed that in and out must be close(), or the file will not be changed.

text file input

  • File
  • FileReader
  • BufferedReader
File infile = new File (inFileName);
BufferedReader in = new BufferedReader (new FileReader(infile));
String s = in.readLine();
in.close();

if readLine() reads nothing, return null;

text file output

  • File
  • FileWriter
  • BufferedWriter
File outfile = new File (outFileName);
BufferedWriter out = new BufferedWriter(new FileWriter(outfile));

out.println(s);

out.close();

text file io example

File infile = new File (inFileName);
File outfile = new File (outFileName);
BufferedReader in = new BufferedReader (FileReader (infile));
BufferedWriter out = new BufferedWriter (FileWriter (outFile));
String string = in.readLine();

while (string != null) {
  out.println(string);
  string = in.readLine();
}

in.close();
out.close();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值