要修改Java Properties文件中的数据,你需要遵循以下步骤:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream("config.properties");
Properties properties = new Properties();
properties.load(fileInputStream);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
properties.setProperty("key", "new_value");
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream("config.properties");
properties.store(fileOutputStream, "Updated properties");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
将以上代码片段组合在一起,你可以创建一个方法来修改Properties文件中的数据。这是一个完整的示例:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class PropertiesModifier {
public static void main(String[] args) {
modifyProperty("config.properties", "key", "new_value");
}
public static void modifyProperty(String filePath, String key, String newValue) {
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
fileInputStream = new FileInputStream(filePath);
Properties properties = new Properties();
properties.load(fileInputStream);
properties.setProperty(key, newValue);
fileOutputStream = new FileOutputStream(filePath);
properties.store(fileOutputStream, "Updated properties");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
将上述代码保存为一个Java类(例如PropertiesModifier.java),并确保config.properties文件位于与Java类相同的目录中。然后运行Java程序,它将修改config.properties文件中的指定键值对。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。