1. 程式人生 > >Io流讀寫檔案

Io流讀寫檔案

public static void main(String[] args) throws Exception{


File file = new File("D:/d.txt");


StringBuilder sb = new StringBuilder();
String s ="";
List<String> list = new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader(file));


while( (s = br.readLine()) != null) {
sb.append(s + "\n");
list.add(sb.toString());
}
br.close();
System.out.println(list.size());

}

try {  
 
            String content = "This is the content to write into file";  
            File file = new File("D:/log.txt");  
            // if file doesnt exists, then create it  
            if (!file.exists()) {  
                file.createNewFile();  
            }  
            FileWriter fw = new FileWriter(file, true);  
            BufferedWriter bw = new BufferedWriter(fw);  
            bw.write(content);  
            bw.flush();  
            bw.close();  
            System.out.println("OK");
        } catch (IOException e) {  
            e.printStackTrace();  
        }