2014年3月29日 星期六

JAVA 讀/寫檔

通常要把 data 寫入一個檔案,步驟是:
先給一個可以寫入的路徑,在這個路徑下 new 一個 file,將這個 file 開成可以寫入的串流 (ex: FileOutPutStream),然後利用這個串流將檔案內容寫入。
至於要寫成什麼格式就看狀況了。
最重要的是最後要記得在寫完後把串流做 close


附上一個不倚賴 JVM 預設編碼讀檔的寫法,因為有時候就是會遇到 server 跟自己程式有衝突的編碼:

/**
     * 讀取指定路徑之檔案內容成字串.
     *
     * @param filePath
     *            檔案路徑.
     * @return String 字串.
     */
    private static String readFile (final String filePath) {
        logger.info("Read filePath: {}", filePath);

        final File file = new File(filePath);
        if (!file.isFile()) {
            throw new IllegalArgumentException( "Path [" + filePath + "] is not a file.");
        }
        // 讀檔要一個個 Byte 讀進來不能 buffer reader 讀.
        // 讀取檔案內容成字串.
        FileInputStream fis = null;
        try {
            final int fileSize = ( int) file.length();
            final byte[] buffer = new byte[fileSize];

            fis = new FileInputStream(file);
            fis.read(buffer);
            fis.close();

            return new String(buffer, "UTF-8");

        } catch (Exception e) {
            logger.error( "Read file stream error.", e);
            throw new RuntimeException( "Read argument file fail. " + filePath, e);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (Exception e) {
                    logger.error( "Close file stream error.", e);
                }
            }
        }
    }

沒有留言: