Java I/O 教程(九) FileWriter和FileReader

indexman發表於2018-01-07

FileWriter


Java FileWriter 用於往檔案中寫入字元資料。
不像FileOutputStream類,你無需轉換字串成位元組陣列,因為它提供了直接寫字串的方法。

類定義

public class FileWriter
extends OutputStreamWriter

建構函式

FileWriter(File file)
Constructs a FileWriter object given a File object.
FileWriter(File file, boolean append)
Constructs a FileWriter object given a File object.
FileWriter(FileDescriptor fd)
Constructs a FileWriter object associated with a file descriptor.
FileWriter(String fileName)
Constructs a FileWriter object given a file name.
FileWriter(String fileName, boolean append)
Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.

方法


請參考:OutputStreamWriter


例子

package com.dylan.io;

import java.io.FileWriter;

/**
 * @author xusucheng
 * @create 2018-01-07
 **/
public class FileWriterExample {
    public static void main(String args[]){
        try{
            FileWriter fw=new FileWriter("D:\\testout.txt");
            fw.write("Welcome to java.io.");
            fw.close();
        }catch(Exception e){System.out.println(e);}
        System.out.println("Success...");
    }
}


FileReader


Java FileReader 用於從檔案中讀取資料。返回字元資料。

類定義

public class FileReader
extends InputStreamReader

建構函式

FileReader(File file)
Creates a new FileReader, given the File to read from.
FileReader(FileDescriptor fd)
Creates a new FileReader, given the FileDescriptor to read from.
FileReader(String fileName)
Creates a new FileReader, given the name of the file to read from.

方法

具體請參考:InputStreamReader

例子

package com.dylan.io;

import java.io.FileReader;

/**
 * @author xusucheng
 * @create 2018-01-07
 **/
public class FileReaderExample {
    public static void main(String args[])throws Exception{
        FileReader fr=new FileReader("D:\\testout.txt");
        int i;
        while((i=fr.read())!=-1)
            System.out.print((char)i);
        fr.close();
    }
}



相關文章