5
I need to save a file to a server using Java
. In my case, I need to save a file json
. I can save a file normally on my computer, but how do I save directly to a remote server? Below is an example that saves a file on my computer. My question is: to save this file on a remote server, how could I do?
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"));
}
}
Depends on how you want to do it. You can do this using various protocols, including FTP, CIFS (used by Windows for folder and file sharing), Webservice, NFS, SCP (Secure copy over SSH), among others.
– cantoni
@Cantoni With which of these protocols has a simpler implementation?
– Duds
Yeah, that’s a good question. Are you doing it to learn or solve something definitive? Using FTP, SCP or NFS requires you to have a program running on the server. CIFS requires you to have SAMBA if you want to use it on Linux. Finally, I believe that Webservice is an option that is platform independent and more in line with the current reality. However, remember that the ideal is that a secure connection is made between the client and the server via HTTPS.
– cantoni
To solve something definitive. I understood, with your tips, I will give a better search. So the best way is through Webservice?
– Duds
@Cantoni I’m running a mobile application using
phonegap
to be able to enjoy the benefit of the Muti-platform, and the exchange of data between systems I am using will be done withjson
, that what I’ve researched is a good solution. I still don’t have much experience with this type of approach and with that I’m having some doubts, and one of them, was this one that I did.– Duds
In this scenario Duds, have no doubt: Webservice in the vein. :-)
– cantoni
Managed to solve your problem?
– durtto
@Eduardoseixas not yet :/
– Duds