首页 > 编程 > Java > 正文

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

2019-11-26 15:46:06
字体:
来源:转载
供稿:网友

复制代码 代码如下:

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();

  }

 }

}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表