简体   繁体   English

使用Java编辑JSON文件,该文件位于远程位置:SSH可用

[英]Editing JSON file using Java ,where file is at remote location: SSH available

I have a JSON file in my linux box (remote). 我的linux框中有一个JSON文件(远程)。 I am using org.json.simple.* library. 我正在使用org.json.simple.*库。 I would like to just update one of the attributes and write it back. 我只想更新其中一个属性并将其写回即可。 In JSON file, I know there is one key with "XXXX" and its value is "YYYY". 在JSON文件中,我知道有一个带有“ XXXX”的键,其值为“ YYYY”。 I want to update its value to "WWWWXYZ". 我想将其值更新为“ WWWWXYZ”。

Below is code snippet on what is done so far 以下是到目前为止已完成的代码片段

Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftp = (ChannelSftp) channel;

InputStream stream = sftp.get(<JSON FILE LOCATION>);
try {
    JSONParser jsonParser = new JSONParser();

    try {

        JSONObject jsonObject = (JSONObject)jsonParser.parse(
            new InputStreamReader(stream, "UTF-8")
        );

        System.out.println(jsonObject.toJSONString());

        jsonObject.put("XXXX", "WWWWXYZ");
        System.out.println(jsonObject.toJSONString());

    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

If you see, I was able to get the JSON file using SSH and then converted that to JSON Object, edited the JSON object. 如果看到的话,我能够使用SSH获取JSON文件,然后将其转换为JSON对象,然后编辑JSON对象。 Now I would like to write back it to the actual file in linux box. 现在,我想将其写回到linux框中的实际文件中。 Please help on how to write back my JSONObject to file, which is located at remote location (my linux box). 请帮助如何将我的JSONObject写回位于远程位置(我的Linux机器)的文件。

如果我正确理解,则应将json对象写入(可选的新)本地文件(请参阅此处的示例 ),然后使用ChannelSftp put方法将远程文件替换为更新的版本。

If you are referring to putting file back to remote server then following code can help you. 如果您是指将文件放回远程服务器,那么以下代码可以为您提供帮助。 You can save modified JSON to one file in your local machine and then transfer that file to remote machine.. 您可以将修改后的JSON保存到本地计算机中的一个文件,然后将该文件传输到远程计算机。

  channel = session.openChannel("sftp");
        channel.connect();            
        channelSftp = (ChannelSftp) channel;
        channelSftp.cd(SFTPWORKINGDIR);
        File f = new File(filename);
        channelSftp.put(new FileInputStream(f), f.getName());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM