欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java文件操作练习代码 读取某个盘符下的文件

程序员文章站 2024-02-22 14:42:04
复制代码 代码如下:import java.io.bufferedreader;import java.io.file;import java.io.fileinputst...

复制代码 代码如下:

import java.io.bufferedreader;
import java.io.file;
import java.io.fileinputstream;
import java.io.filenotfoundexception;
import java.io.filereader;
import java.io.ioexception;
import java.io.inputstream;
import java.io.reader;

public class ioread {

 /**
  * @param args
  * 文件的读写
  */
 public static void main(string[] args) {
  // todo auto-generated method stub
  try {

   // 方法一

   bufferedreader br = new bufferedreader(new filereader(new file(

   "d:/project/transfar/doc/1.txt")));

   // stringbuilder bd = new stringbuilder();

   stringbuffer bd = new stringbuffer();

   while (true) {

    string str = br.readline();

    if (str == null) {

     break;

    }
    system.out.println(str);

    bd.append(str);

   }

   br.close();

   // system.out.println(bd.tostring());

   // 方法二

   inputstream is = new fileinputstream(new file("d:/project/transfar/doc/1.txt"));

   byte b[] = new byte[integer.parseint(new file("d:/project/transfar/doc/1.txt").length()

   + "")];

   is.read(b);
   system.out.write(b);

   system.out.println();

   is.close();

   // 方法三

   reader r = new filereader(new file("d:/project/transfar/doc/1.txt"));

   char c[] = new char[(int) new file("d:/project/transfar/doc/1.txt").length()];

   r.read(c);

   string str = new string(c);

   system.out.print(str);

   r.close();

  } catch (runtimeexception e) {

   // todo auto-generated catch block

   e.printstacktrace();

  } catch (filenotfoundexception e) {

   // todo auto-generated catch block

   e.printstacktrace();

  } catch (ioexception e) {

   // todo auto-generated catch block

   e.printstacktrace();

  }

 }

}