0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

JavaでINIファイルの読み書き(セクション非対応)

Posted at

javaでINIファイルを読み書きする

JavaでINIファイルの読み書きをします、セクション非対応です
諸事情により古いJavaで作ったので Files.writeString, Files.readString を使用していません

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

class IniFile {
    public static void Write(String fileName, HashMap<String, String> x) throws Exception {
        String y = "";
        for(String k : x.keySet()) {
            y += k + "=" + x.get(k) + "\n";
        }
        //Files.writeString(Paths.get(fileName), y, StandardCharsets.UTF_8);
        List<String> yline = new ArrayList<String>();
        yline.add(y);
        Files.write(Paths.get(fileName), yline, StandardCharsets.UTF_8);
    }
    
    public static HashMap<String, String> Read(String fileName) throws Exception {
        HashMap<String, String> y = new HashMap<>();
        Path file = Paths.get(fileName);
        //String x = Files.readString(file, Charset.forName("UTF-8"));
        byte[] bytes = Files.readAllBytes(file);
        String x = new String(bytes, Charset.forName("UTF-8"));
        String[] lines = x.split("[\r\n]");
        for(String l: lines) {
            String[] a = l.split("=", 2);
            if(a.length == 2) {
                y.put(a[0].trim(), a[1].trim());
            }
        }
        return y;
    }
};
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?