ファイルの読み込む(java)

来源:互联网 发布:为知笔记无法打开 编辑:程序博客网 时间:2024/06/16 23:27

①ファイルから、データを読み込む、固定バイト数を取得する。

 

RandomAccessFile rdFile = null;

rdFile = new RandomAccessFile(file, "r");

byte[] lines = new byte[100];

int i = 0;

 

while (rdFile.read(lines) != -1) {

String number1 = trimSpace(new String(lines, 0, 12));

String number2 = trimSpace(new String(lines, 12, 100));

rdFile.seek(i * 100);

}

 

    /**
     * 前、後全角・半角スペースを除く
     * @param str 文字列
     * @return 変換した文字列
     */
 private static String trimSpace(String str) {
        if (StringUtil.isEmpty(str)) {
            return "";
        }
     return str.replaceAll("^[//s | ]*", "").replaceAll("[//s | ]*$", "");
}

 

②ファイルの作成し、charsetを指定する。

 

 

                File file1 = new File(dir + "/" + fileName);
                OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(file1), charset);
                if (csvStringBuffer != null && !StringUtil.isEmpty(csvStringBuffer.toString())) {
                    out.write(csvStringBuffer.toString());
                }
                out.close();