Os exemplos deste artigo compartilham o código de upload de imagem Java para sua referência. O conteúdo específico é o seguinte
importar java.io.*; importar java.net.*; /**Enviar final*/ class PicsEnd {public static void main (string [] args) lança exceção {if (args.length! = 1) {System.out.println ("Selecione uma imagem .jpg"); retornar; } Arquivo de arquivo = novo arquivo (args [0]); if (! (file.exists () && file.isfile ())) {System.out.println ("Há um problema com a imagem (não um arquivo ou não existe)"); retornar; } if (! file.getName (). ENDSWITH (". retornar; } if (file.length ()> 1024*1024*10) {System.out.println ("A imagem é muito grande e não pode ser carregada"); retornar; } Soquete s = new Socket ("192.168.33.1", 10006); // Crie um serviço FileInputStream fis = new FileInputStream ("d: //beauty.jpg"); // leia a imagem outputStream out = s.getUttStream (); // write readed por [] int len = 0; while ((len = fis.read (b))! = -1) {out.write (b, 0, len); } s.shutdownoutput (); // tag final inputStream em = s.getInputStream (); // O servidor de leitura retorna dados byte [] bin = new byte [1024]; int num = in.read (bin); System.out.println (new String (bin, 0, num)); fis.close (); S.Close (); }} classe picThread implementa Runnable {private Socket S; picthread (soquete s) {this.s = s; } public void run () {int count = 1; String ip = s.getineTAddress (). InputStream in = s.getInputStream (); // Leia os dados no arquivo de fluxo de arquivo = novo arquivo (ip+"("+(count)+")"+". Jpg"); while (file.exists ()) // Determine se o arquivo existe arquivo = novo arquivo (ip+"("+(count ++)+")"+". jpg"); FileOutputStream fos = new FileOutputStream (FILE); // grava byte [] b = novo byte [1024]; int len = 0; while ((len = in.read (b))! =-1) {fos.write (b, 0, len); } OutputStream Out = s.getOutputStream (); // grava dados transmitidos ao servidor Out.Write ("Carregado com sucesso!" .GetBytes ()); fos.close (); S.Close (); } catch (Exceção e) {lança a nova RunTimeException ("Falha no upload"); }}} /**Server* / classe picrece {public static void main (string [] args) lança exceção {serversocket ss = new ServerSocket (10006); while (true) {soquete s = ss.accept (); // recebe novo thread (novo picthread (s)). start (); }}}Efeito:
O exposto acima é tudo sobre este artigo, espero que seja útil para todos aprenderem a programação Java.