icsnowing 发表于 2013-2-7 08:17:09

转Java中各种文件操作方法

java中的读文件
http://www.cn-java.com/www1/?uid-555218-action-viewspace-itemid-5256

使用FileReader和FileWriter读取写入文件内容
http://www.cublog.cn/u/20665/showart_205294.html

1、Java的輸入与輸出

import java.io.DataInputStream;
import java.io.IOException;
public class InputAndOutput {
public static void main(String args[]) throws IOException {
//    int a;
//    System.out.println("请输入任一字符:");
//    a=(char)System.in.read();
//    System.out.println("你输入的字符是"+(char)a);
//   


//DataInputStream str1=new DataInputStream(System.in);

//用BufferedReader 取代DataInputStream

BufferedReader str2 = new BufferedReader(new InputStreamReader(System.in));
   String a;
   System.out.print("请输入一字符串:");
// a=str1.readLine();

//此方法已过时,用BufferedReader替代.方法无法将字节正确转换为字符

   a=str2.readLine();
   System.out.println("你输入的字符串是"+a);
   str2.close();//注意用了之后一定要close inputstream
}
}

2、java 中的字节流不能直接操作Unicode字符,要想直接操作字符输入/输出要使用几个字符输入/输出类。

字符流层次结构的顶层是Reader和Writer抽象类。

1、Reader

    Reader是定义java的流式字符输入模式的抽象类。错误异常为IOException。

    主要方法有:

    abstractvoidclose() 关闭输入流,关闭后读取将会产生IOException异常。

    voidmark(int numChars) 在输入流的当前位置设立一个标志。该输入流在numChars个字符被读取前有效。

    boolean markSupported() 该流支持mark()/reset()则返回true。

    int read() 如果调用的输入流的下一个字符可读则返回一个整型,文件尾返回-1。

    int read(char buffer[ ]) 试图读取buffe中的buffer.length个字符,返回实际成功读取的字符数,文件尾返回-1。

    abstract int read (char buffer[ ], int offset, int numChars) 试图读取buffer中从buffer开始的 numChars个字符,返回实际成功读取的字符数,文件尾返回-1。

    void reset()设置输入指针到先前设立的标志处。

    long skip (long numChars) 跳过numChars 个输入字符,返回跳过的字符数。

2、writer

    writer 是定义流矢字符输出的抽象类。所有该类的方法都返回一个void值并在出错条件下引发一个IOException异常。

    主要方法:

    abstract void close()关闭输出流,关闭后的写操作引发IOException异常。

    abstract void flush(0定制输出状态以使每个缓冲器都被清除。也就是刷新缓冲。

    voidwrite(int ch) 向输出流写入单个字符。参数是一个整型,可以不必把参数转换成字符型就可以调用。

    void write (char buffer[ ]) 向一个输出流写入一个完整的字符数组。

    abstract void write (char buffer[ ], int offset ,int numChars)向调用的输出流写入数组buffer 以buffer为起点的numChars个字符区域内的内容。

    void write(String str)向调用的输出流写str。

    void write (String str, int offset, int numChars) 写数组str中以制定的offset为起点的长度为numChars个字符区域内的内容。

3、FileReader

    FileReader类创建了一个可以读取文件内容的Reader类。它的构造函数:

    FileReader (String filePath)filePath 是一个文件的完整路径

    FileReader(File fileObj)fileObj 是描述该文件的File对象

    均引发FileNotFoundException异常。

    例如,从一个文件逐行读取并把它输出到标准输入流。

    importjava.io.*;

    class FileReaderDemo {

      public static void main (String args[ ] ) throws Exception {

            FileReader fr =new FileReader ("c:\\in.txt");

//FileReader fr =new FileReader ("c:/in.txt");这句也可以改为这样

            BufferedReader br = new BufferedReader (fr);

            String s;

             while ((s = br.readLine() )!=null) {

               System.out.prinln (s);

            }

//如果改为这样是不行的,这样不会报错,但是運行结果将为null;

//因为读流文件时是按一个个字符读的,所以必要先定义一个string

//while(bf.readLine()!=null){
//System.out.println(bf.readLine());
// }

            fr.close();//注意用过的流文件最后都要关闭

      }

    }

4、用OutputStream 将得到的字符串写入指定的文件(本人習慣用这种方法,至于以下的第5种方法FileWriter,我基本上不用,按个人爱好而已)

public static void main(String args[]) throws IOException {

   String source = "我是田平";
   byte [] bytes = source.getBytes();//一定由string得到bytes才能写入到文件里
   OutputStream os = new FileOutputStream("c:/1.txt");
   os.write(bytes);//将字节一个个写入文件
   os.close();

}

5、FileWriter

    FileWriter 创建一个可以写文件的Writer类。构造函数:

    FileWriter (String filePath)filePath 是一个文件的完整路径

    FileWriter(String filePath, boolean append)如果append为true ,输出是附加到文件尾的。

    FileWriter(File fileObj)是描述该文件的File对象

// 字符串 I/O 操作,字符与字节转换操作。
// 在 Java 包 java.io.* 中,
// 以“Stream”结尾的类一般是用来操作“字节串”的类,如FileOutputStream等
// 以“Reader”,“Writer”结尾的类一般是用来操作“字符串”的类。
public static voidmain (String args[ ]) throws Exception {
   //author by jeantian
String source = "我是田平";         
byte[] buffer=source.getBytes("GB2312");// 按照 GB2312 得到字节(得到多字节字符串)
source=new String(buffer,"GB2312");// 从字节按照 GB2312 得到UNICODE 字符串
// 要将 String 按照某种编码写入文本文件,有两种方法:第一种为
FileWriterf1 = new FileWriter("c:/file1.txt");
// 如果String是中文的话,用FileWriter易产生乱码,但是用FileOutputStream不会产生乱码
//   for(int i=0; i<buffer.length; i++) {
//   f1.write (buffer);//如果是英文,将字节一个个写入指定的文件 用这句可以写
//   }
f1.write (source);//如果是中文,用这句可以写入显示中文,按上面的话就会显示乱码
f1.close();
System.out.println("file1写入成功");

            
//要将 String 按照某种编码写入文本文件,构造指定编码的 Writer 来写入字符串
//第二种情况中文英文都不会产生乱码
Writer ow = new OutputStreamWriter(new FileOutputStream ("c:/file2.txt"),"GB2312");
   ow.write(source);
   ow.close();
   System.out.println("file2写入成功");
    }
}

评论:
java.io.DataInputStream
String readLine()
          已过时。 该方法无法将字节正确转换为字符。从 JDK 1.1 开始,读取文本行的首选方法是使用 BufferedReader.readLine() 方法。对于使用 DataInputStream 类读取文本行的程序,可以转而使用 BufferedReader 类,实现方式是通过将以下形式的代码:
   DataInputStream d = new DataInputStream(in);
替换为:
   BufferedReader d
          = new BufferedReader(new InputStreamReader(in));

// 如果String是中文的话,用FileWriter易产生乱码,但是用FileOutputStream不会产生乱码...如果你要用FileWriter的话,可能是你的eclipse的编译环境和运行环境没有设为UTF-8,在我这里没有显示乱码的情况..


判断文件是否为空?读取文件?
http://www.360doc.com/showWeb/0/0/19842.aspx

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
*
* 先判断文件是否存在,然后判断文件是否为空。
* 如果存在且不为空,则输出文件内容在控制台。
*
* @author rmouse_2005   
* @data 2005-10-14   
* @version 1.0
*/

public class Test {

/**
*
* Test类主函数
*
* @param args
* @throws IO异常
*/
public static void main(String[] args) throws IOException {
String path = "h:\\eclipse\\test\\a.txt";
Test t = new Test();
if (t.isExist(path)) {
   if (t.isEmpty(path)) {
    System.out.println("success!");
    System.out.println();
    t.getValue(path);
   } else {

    System.out.println("false!");
   }
} else {
   System.out.println("false!");
}
}

/**
*
* 判断文件是否存在
*
* @param file 文件名
* @return 文件是否存在
* true - 文件存在
* false - 文件不存在
*/
boolean isExist(String file) {
File f = new File(file);
if (f.exists()) {
   System.out.println("File is Exist!");
   return true;
} else {
   System.out.println("File isn't Exist!");
   return false;
}
}

/**
*
* 判断文件是否为空
*
* @param file 文件名
* @return 文件是否为空
* true - 文件为空
* false - 文件不为空
* @throws IO异常
*/
boolean isEmpty(String file) throws IOException {
FileReader fr = new FileReader(file);
if (fr.read() == -1) {
   System.out.println("File is Empty!");
   return false;
} else {
   System.out.println("File isn't Empty!");
   return true;
}
}

/**
*
* 读取文件
*
* @param file 文件名
* @throws IO异常
*/
void getValue(String file) throws IOException {
FileReader fr;
fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = "";
line = br.readLine();
while (line != null) {
   String lineNew = "";
   lineNew = line;
   System.out.println(lineNew);
   line = br.readLine();
}
}
}
页: [1]
查看完整版本: 转Java中各种文件操作方法