当前位置: 移动技术网 > IT编程>开发语言>Jsp > Java 中对文件的读写操作之比较

Java 中对文件的读写操作之比较

2018年12月27日  | 移动技术网IT编程  | 我要评论
java 中对文件的读写操作之比较

作者:jeru liu
日期:november 29,2000
版本:1.0

纪念在china积分过一百呕心原创一篇(java 中对文件的读写操作之比较)拿分好难呀,555~~~,不知道那些几千分的老妖们是怎么灌水的。

java 对文件进行读写操作的例子很多,让初学者感到十分困惑,我觉得有必要将各种方法进行
一次分析,归类,理清不同方法之间的异同点。

一.在 jdk 1.0 中,通常是用 inputstream & outputstream 这两个基类来进行读写操作的。
inputstream 中的 fileinputstream 类似一个文件句柄,通过它来对文件进行操作,类似的,在
outputstream 中我们有 fileoutputstream 这个对象。

用fileinputstream 来读取数据的常用方法是:
fileinputstream fstream = new fileinputstream(args[0]);
datainputstream in = new datainputstream(fstream);
用 in.readline() 来得到数据,然后用 in.close() 关闭输入流。
完整代码见 example 1。

用fileoutputstream 来写入数据的常用方法是:
fileoutputstream out out = new fileoutputstream("myfile.txt");    
printstream p = new printstream( out );
用 p.println() 来写入数据,然后用 p.close() 关闭输入。
完整代码见 example 2。


二.在 jdk 1.1中,支持两个新的对象 reader & writer, 它们只能用来对文本文件进行操作,而
jdk1.1中的 inputstream & outputstream 可以对文本文件或二进制文件进行操作。

用filereader 来读取文件的常用方法是:
filereader fr = new filereader("mydata.txt");
bufferedreader br = new bufferedreader(fr);
用 br.readling() 来读出数据,然后用br.close() 关闭缓存,用fr.close() 关闭文件。
完整代码见 example 3。

用 filewriter 来写入文件的常用方法是:
filewriter fw = new filewriter("mydata.txt");
printwriter out = new printwriter(fw);  
在用out.print 或 out.println 来往文件中写入数据,out.print 和 out.println的唯一区别是后者写
入数据或会自动开一新行。写完后要记得 用out.close() 关闭输出,用fw.close() 关闭文件。   
完整代码见 example 4。

-------------------------------------------------------------- following is the source code of examples------------------------------------------------------

example 1:
// fileinputdemo
// demonstrates fileinputstream and datainputstream
import java.io.*;

class fileinputdemo {
  public static void main(string args[]) {
    // args.length is equivalent to argc in c
    if (args.length == 1) {
      try {
        // open the file that is the first command line parameter
        fileinputstream fstream = new fileinputstream(args[0]);
        // convert our input stream to a datainputstream
        datainputstream in = new datainputstream(fstream);
        // continue to read lines while there are still some left to read
        while (in.available() !=0) {
          // print file line to screen

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网