疯狂java


您现在的位置: 疯狂软件 >> 新闻资讯 >> 正文

java基本文件的读写


 

   

  读取某个盘符下的文件代码中要求的是绝对路径。

  1. [代码]编译过程中要注意绝对路径问题和异常的抓取

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

  }

  }

  }