- 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();
- }
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/2303201511956.html
来源: http://www.codesnippet.cn/detail/2303201511956.html