Questo è un pezzo della parte Client di un programmino java per inviare file... [scusate la formattazione]
Ma funziona solo per i file di testo (non per immagini, file audio...)
Ho provato ad usare FileInputStream ma niente da fare...
I file (non di testo) che invia hanno la stessa dimensione solo che all'interno alcuni byte risultano diversi, ecco perchè il file inviato risulta non funzionante.
Come posso risolvere?
codice:
public void run() {
Socket echoSocket = null;
PrintWriter out = null;
// BufferedReader in = null;
InputStream in = null;
FileOutputStream out_f = null;
// long dim2=0;
int port = Integer.parseInt(Tporta);
try {
echoSocket = new Socket(ip, port);
out = new PrintWriter(echoSocket.getOutputStream(), true);
// in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
in = echoSocket.getInputStream();
}
catch (UnknownHostException e) {
System.err.println("Non conosco l'host");
System.exit(1);
}
catch (IOException e) {
System.err.println("Non posso ottenere I/O per la connessione con: localhost");
System.exit(1);
}
out.println(filename);
out.flush();
File outputFile = new File(shareFolder + "//" + "_INCOMPLETE_" + filenew);
File overFile = new File(shareFolder + "//" + filenew);
try {
out_f = new FileOutputStream(outputFile);
//dim2 =Long.parseLong(in.readLine());
// dim2 =in.read();
}
catch (IOException e) {
e.printStackTrace();
}
vecchio.setText(nuovo.getText());
nuovo.setText("Download del file: " + filenew + " : " + dim);
try {
//for(int k=0; k<dim2; k++)
// out_f.write(in.read());
int c;
while ((c=in.read())!=-1) { out_f.write(c); }
}
catch (IOException e) {
e.printStackTrace();
}
try {
out_f.close();
out.close();
in.close();
echoSocket.close();
}
catch (IOException e) {
e.printStackTrace();
}
questa è la relativa parte Server
codice:
public void run(){
try {
InputStream i = client.getInputStream();
OutputStream o = client.getOutputStream();
in = new BufferedReader(new InputStreamReader(i));
output = new PrintWriter(o);
String s = null;
s = shareFolder + "\\" + in.readLine();
System.out.println(s);
File inputFile = new File(s);
FileInputStream in_f = new FileInputStream(inputFile);
int c;
while ((c = in_f.read()) != -1 ) { output.write(c); output.flush();}
//long dim = inputFile.length();
//output.println(dim);
output.flush();
// for(int k=0; k<inputFile.length(); k++){
// output.write(in_f.read());
// output.flush();
// }
in_f.close();
} catch (Exception e) {
System.out.println("Errore");
System.exit(1);
} finally {
System.out.println ("Connessione chiusa");
try {
client.close();
} catch (Exception e) {
System.exit(1);
}
}
}
}
grazie a tutti