LoginSignup
0
0

More than 5 years have passed since last update.

Java ばらばらの文字コードを一括で同じ文字コードに変換

Last updated at Posted at 2019-01-23

Java ファイルのばらばらの文字コードを一括で同じ文字コードに変換して保存

    public void writeFile() throws IOException {
        Files.list(Paths.get("dir"))
            .filter(p -> p.toFile().getName().endsWith(".txt"))
            .forEach(p -> writeFile(p));

        Files.find(Paths.get("dir")
                , Integer.MAX_VALUE
                , (p, a) -> p.toFile().getName().endsWith(".txt"))
            .forEach(p -> writeFile(p));
    }

    public void writeFile(Path path) {
        try {
            Files.write(path
                    , readFile(path).stream().collect(Collectors.joining("\r")).getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            throw new IllegalStateException("write error file : " + path.toAbsolutePath(), e);
        }
    }

    public List<String> readFile(Path path) {
        for (Charset charset: Charset.availableCharsets().values()) {
            try {
                return Files.readAllLines(path, charset);
            } catch (MalformedInputException e) {
                e.printStackTrace();
                continue;
            } catch (IOException e) {
                throw new IllegalStateException("read error file : " + path.toAbsolutePath(), e);
            }
        }
        throw new IllegalStateException("read error file : " + path.toAbsolutePath());
    }
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0