How to save files to a server via Java?

5

I need to save a file to a server using Java . In my case, I need to save a json file. Can I save a file normally on my computer, but how do I save directly to a remote server? Here is an example that saves a file to my computer. My question is: to save this file to a remote server, how could I do it?

public class EstudoJSON {

    public static void main(String[] args) throws IOException {
        JSONObject json = adicaoSimplesDeDados ();

        FileWriter file = new FileWriter("json//javaJSON.json");
        file.write(json.toString());
        file.flush();
        file.close();

        System.out.println(json.toString());

        adicaoDeUmObjeto ();
    }

    public static JSONObject adicaoSimplesDeDados () {
        Carro carro = new Carro();
        carro.setId(1l);
        carro.setModelo("Celta");
        carro.setPlaca("AAA1234");

        //Criacao do objeto carroJson
        JSONObject carroJson = new JSONObject();
        //Insercao de valores do carro no objeto JSON
        carroJson.put("id", carro.getId());
        carroJson.put("Modelo", carro.getModelo());
        carroJson.put("Placa", carro.getPlaca());

        System.out.println(carroJson);
        System.out.println(carroJson.get("Modelo"));

        return carroJson;
    } 

    public static void adicaoDeUmObjeto () {
        Carro carro = new Carro();
        carro.setId(1l);
        carro.setModelo("Ka");
        carro.setPlaca("AAA1234");

        JSONObject carroJson = new JSONObject();
        carroJson.put("Carro", carro);

        System.out.println(carroJson);
        System.out.println(carroJson.get("Carro"));
    }

}
    
asked by anonymous 02.12.2015 / 16:45

2 answers

1

If the program is running on your machine and should save a file on a remote machine, that remote machine must have a form of access such as FTP, SSH or otherwise as quoted in the comments.

If the Java program is already on the server, then it is like saving locally. Just an interface for example Web (HTML).

If there are two Java programs, one on your machine and another on the server, you can use Socket or WebService. A client program would send data to the program on the server that would save the file or if it is just JSON can save in the database as normal text or objects. In this third case it is what a JSON REST WebService does.

    
30.05.2016 / 19:45
0

You could create a web service (rest) and save json to a database that stores json, such as mongodb.

    
03.12.2015 / 13:16