StackAsk is a community where developers ask questions, share answers and learn from each others real-world experience, so every solved problem helps the next person who runs into it.
public class OutputSjis { private final static byte CR = 0x0d; // 13 private final static byte LF = 0x0a; // 10 public static void main(String[] args) { output(); } /** * sjisファイル出力処理 * 参考サイト * <li>http://www.ne.jp/asahi/hishidama/home/tech/java/files.html */ private static void output() { // 出力先のディレクトリ。無ければ親を含めて作成する Path dir = Paths.get("work"); if (Files.notExists(dir)) { try { Files.createDirectories(dir); } catch (IOException e) { } } // 出力先のファイル Path path1 = dir.resolve("sjis1.txt"); Path path2 = dir.resolve("sjis2.txt"); Path path3 = dir.resolve("sjis3.txt"); Path path4 = dir.resolve("sjis4.txt"); File file1 = path1.toFile(); File file2 = path2.toFile(); // 仮データ作成 List dataList = new ArrayList(); dataList.add("あいうえお"); dataList.add("~"); // 良く文字化けするやつ dataList.add(" "); // MS932では変換出来ない文字(ソースファイルはUTF8である必要がある) dataList.add("かきくけこ"); dataList.add("~-¢£¬―∥"); // 【パターン1】元データがByteで来る場合を想定 try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file1))) { for (String data : dataList) { // 「MS932」はエイリアスで、正式名は「windows-31j」 // 「SJIS」はエイリアスで、「Shift_JIS」が正式名 byte[] bb = data.getBytes(Charset.forName("MS932")); bos.write(bb); bos.write(CR); // CR bos.write(LF); // LF bos.flush(); } } catch (IOException e) { } // 【パターン2】元データがStringで来る場合を想定 try (PrintWriter pw = new PrintWriter( new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file2), Charset.forName("MS932"))))) { for (String data : dataList) { pw.println(data); } } catch (IOException e) { } // 【パターン3】パターン1は、java8ではこう書ける try (OutputStream os = Files.newOutputStream(path3)) { for (String data : dataList) { byte[] bb = data.getBytes(Charset.forName("MS932")); os.write(bb); os.write(CR); // CR os.write(LF); // LF os.flush(); } } catch (IOException e) { } // 【パターン4】パターン2は、java8ではこう書ける // ただし、パターン2ではエンコード出来ない文字が?で出力されるのに対して、こっちはUnmappableCharacterExceptionが投げられる try (BufferedWriter bw = Files.newBufferedWriter(path4, Charset.forName("MS932"))) { for (String data : dataList) { bw.write(data); bw.newLine(); } } catch (IOException e) { } } }
2.2K Point(s)
1.2K Point(s)
313 Point(s)
178 Point(s)
138 Point(s)
Your account is signed in on the device(s) below. Sign out of at least one of them to continue signing in on this device.
Your account is signed in on the device(s) below. Sign out directly on one of those devices, or wait until the sign-in again time shown below.
If you cant access those devices, please contact the administrator to sign them out for you.
Input your email to receive reset password link, or if you remember your password, you can click