java文件的I/O
【原创】
java文件的I/O操作,简单来说就是向文件中写入数据以及从文件中读出数据,这是我们平日做的最多的操作,这里给出两种文件I/O操作,当然还有许多的操作方法,各种流的使用,可谓是高深莫测;不管了,直接怼代码:
1 package com.jiajia.filedemo; 2 3 import java.io.BufferedReader; 4 import java.io.BufferedWriter; 5 import java.io.File; 6 import java.io.FileInputStream; 7 import java.io.FileOutputStream; 8 import java.io.FileReader; 9 import java.io.FileWriter; 10 import java.io.InputStreamReader; 11 import java.io.OutputStreamWriter; 12 13 public class Demo_1 { 14 public static void main(String[] args) throws Exception{ 15 String filename_input = "/Users/fanjiajia/Desktop/temp"; 16 String filename_output = "/Users/fanjiajia/Desktop/temp2.txt";//若temp1不存在,他会自己给你创建一个 17 String str = read_1(filename_input); 18 System.out.println(str); 19 writer_2(str, filename_output); 20 } 21 /** 22 *文件读取方法一 23 * @param filename 24 * @return 25 * @throws Exception 26 */ 27 public static String read_1(String filename) throws Exception{ 28 File f = new File(filename); 29 FileInputStream f_in = new FileInputStream(f); 30 InputStreamReader isr = new InputStreamReader(f_in); 31 BufferedReader buf_reader = new BufferedReader(isr); 32 String s; 33 StringBuilder sb = new StringBuilder(); 34 while((s=buf_reader.readLine())!=null){ 35 sb.append(s+"\n"); 36 } 37 buf_reader.close(); 38 isr.close(); 39 f_in.close(); 40 return sb.toString(); 41 } 42 /** 43 * 文件读取方法二 44 * @param filename 45 * @return 46 * @throws Exception 47 */ 48 public static String read_2(String filename) throws Exception { 49 FileReader filereader = new FileReader(filename); 50 BufferedReader in = new BufferedReader(filereader); 51 String s ; 52 StringBuilder sb = new StringBuilder(); 53 while((s=in.readLine())!=null){ 54 sb.append(s+"\n"); 55 } 56 in.close(); 57 filereader.close(); 58 return sb.toString(); 59 } 60 61 /** 62 * 文件写入方法一 63 * @param str 64 * @param filename 65 * @throws Exception 66 */ 67 public static void writer_1(String str,String filename ) throws Exception{ 68 //将给定的字符串输出到filename文件中 69 FileWriter f_writer = new FileWriter(filename); 70 BufferedWriter buf_writer = new BufferedWriter(f_writer); 71 buf_writer.write(str); 72 buf_writer.close(); 73 f_writer.close(); 74 } 75 /** 76 * 文件写入方法二 77 * @param str 78 * @param filename 79 * @throws Exception 80 */ 81 public static void writer_2(String str,String filename) throws Exception{ 82 File f = new File(filename); 83 FileOutputStream f_os = new FileOutputStream(f); 84 OutputStreamWriter os = new OutputStreamWriter(f_os); 85 BufferedWriter buf_writer = new BufferedWriter(os); 86 buf_writer.write(str); 87 buf_writer.close(); 88 os.close(); 89 f_os.close(); 90 } 91 }
很明显直接使用FileReader 和 FileWriter这两个类并结合BufferedReader/BufferedWriter很方便
其实FileWriter类的对象w直接就可以write,并且在创建是=时候,如果是new FileWriter(。。。,true);第二个参数为true的话,便是在文件末尾写;
转载请注明出处:http://www.cnblogs.com/numen-fan/