目录
申请读写权限:
build.gradle中添加库引用:
android java读写yaml文件
java修改yaml文件 YamlFile:
修改yaml文件方法2 Yaml:
删除值:
申请读写权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
build.gradle中添加库引用:
dependencies {/** 日志库 **/implementation 'androidx.core:core-ktx:1.2.0'implementation 'androidx.appcompat:appcompat:1.1.0'// 集成日志库api 'com.jakewharton.timber:timber:5.0.1'implementation 'org.yaml:snakeyaml:1.33'api 'com.google.code.gson:gson:2.8.5'api 'com.squareup.okhttp3:okhttp:4.9.1'implementation 'com.alibaba:fastjson:2.0.28'
}
android java读写yaml文件
import org.simpleyaml.configuration.file.YamlFile;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;private static void run() {File file = new File("/data/data/com.xx/files/config.yaml");if (file.exists()) {YamlFile yamlFile = new YamlFile(file);try {yamlFile.load();int debug = yamlFile.getInt("debug", 1);
// Timber.i("debug: " + debug);Timber.i("debug: %s", debug);} catch (IOException e) {}}Map<String, Object> data = new HashMap<>();data.put("name", "John Doe");data.put("age", 30);DumperOptions options = new DumperOptions();options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);Yaml yaml = new Yaml(options);try (FileWriter writer = new FileWriter("path_to_your_file.yaml")) {yaml.dump(data, writer);} catch (IOException e) {e.printStackTrace();}}
写文件可以参考下面的:java修改yaml文件 YamlFile
java修改yaml文件 YamlFile:
private void modfiy_param(String key ,int value) {File file = new File("/data/data/com.xx/files/config.yaml");if (file.exists()) {YamlFile yamlFile = new YamlFile(file);try {yamlFile.load();int track_delay = yamlFile.getInt("aaa", 1);Timber.i("aaa: %s", aaa);yamlFile.set(key, value);yamlFile.save();} catch (IOException e) {e.printStackTrace();}}
}
修改yaml文件方法2 Yaml:
Yaml yaml = new Yaml();Map<String, Object> data = null;try {data = yaml.load(new FileInputStream("/data/data/com.xx/files/config.yaml"));// 2. 修改这个对象data.put("name", "Jane Doe");
// Map<String, Object> data = new HashMap<>();data.put(key, value);FileWriter writer = new FileWriter("/data/data/com.xx/files/config.yaml");yaml.dump(data, writer);} catch (FileNotFoundException e) {throw new RuntimeException(e);} catch (IOException e) {throw new RuntimeException(e);}
删除值:
import org.yaml.snakeyaml.Yaml;import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;public class Main {public static void main(String[] args) {deleteFromYamlFile("path_to_your_file.yaml", "name");}public static void deleteFromYamlFile(String filePath, String key) {Yaml yaml = new Yaml();try {// 1. 读取文件并将其解析为一个对象Map<String, Object> data = yaml.load(new FileInputStream(filePath));// 2. 从这个对象中删除一个键data.remove(key);// 3. 将修改后的对象写回到文件FileWriter writer = new FileWriter(filePath);yaml.dump(data, writer);writer.close();} catch (IOException e) {e.printStackTrace();}}
}