服务器返回非法容量-1

时间:2014-05-30 17:00:27

标签: java android sockets

在这里,我将发布一个完美的例子,通过套接字发送和接收图像,音乐,视频或任何东西,以便谁可以使用它。它几近完美。它完成了这项工作,无论你在目标中拥有多少文件,它们都会计算它们并将它们发送到java服务器,但是我在服务器端收到一个例外:

 Exception in thread "main" java.lang.IllegalArgumentException: Illegal Capacity: -1
at java.util.ArrayList.<init>(Unknown Source)

我真的不知道那是什么,但我很感激,如果你帮忙的话,我会为自己和任何一个发现自己需要一个人的人来说这个。感谢

Android Cliend:

 package com.example.imagesender;

//File imagefile = new File(filepath);
//  FileInputStream fis = null;
//       try {
//           fis = new FileInputStream(imagefile);
//      } catch (FileNotFoundException e) {
 //          System.out.println("file not found");
 //        e.printStackTrace();
 //    }

 // Bitmap bm = BitmapFactory.decodeStream(fis);
//  imgbyte = new byte [(int)filepath.length()];
//   imv.setImageBitmap(bm);
//  Log.d("ClientActivity","length:"+imgbyte);




public class AccountCreator extends Activity {  
    private Button send;  

    private Socket socket;  
    private File f,fdst;  
    private FileInputStream fin,fises;  
    private static Context context;  

    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.mes_registerpage);  
        send=(Button)findViewById(R.id.sendpic);  
      //  sendWan=(Button)findViewById(R.id.sendWan);  
        AccountCreator.context = getApplicationContext();  

        send.setOnClickListener(new OnClickListener(){  

            public void onClick(View view){  

                this.doit();
            }
                class myAsync extends AsyncTask<String, Boolean, Boolean>{


                                 @Override
                    protected Boolean doInBackground(String...urls){    
                try {  
                    socket = new Socket("10.0.2.2", 1500);  
                    System.out.println(socket);  
                    System.out.println("Connecting...");  


                    File fil=new 
 File(Environment.getExternalStorageDirectory()+"/Pictures/");  
                      System.out.println(fil);
                    File[] Files=fil.listFiles();  
                    System.out.println(Files);
                    for (int count=0;count < Files.length;count ++){  
                        System.out.println(Files[count].getName());  

                    }  

                    OutputStream os = socket.getOutputStream();    
                    DataOutputStream dos = new DataOutputStream(os);   

                    dos.writeInt(Files.length);  

                    for (int count=0;count<Files.length;count ++){  
                          dos.writeUTF(Files[count].getName());  

                    }  
                    for (int count=0;count<Files.length;count ++){  

                          int filesize = (int) Files[count].length();  
                          dos.writeInt(filesize);  
                    }  

                    for (int count=0;count<Files.length;count ++){  

                    int filesize = (int) Files[count].length();  
                    byte [] buffer = new byte [filesize];  

                    FileInputStream fis = new  
 FileInputStream(Files[count].toString());    
                    BufferedInputStream bis = new BufferedInputStream(fis);    

                    //Sending file name and file size to the server    
                    bis.read(buffer, 0, buffer.length); //This line is important  
                    dos.write(buffer, 0, buffer.length);     
                    dos.flush();   

                    //close socket connection  
                    //socket.close();  

                }  

                           //  Toast.makeText(getApplicationContext(),"Transfer file 
is completed!!", Toast.LENGTH_LONG).show();   
                     socket.close();  
                }  
                catch(Exception e){  
                    System.out.println("Error::"+e);  
                    //System.out.println(e.getMessage());  
                    //e.printStackTrace();  
                    //Log.i("******* :( ", "UnknownHostException");  
                }
                return null;

            }  
                }



                protected void onPostExecute(String result){
                }


public void doit(){
myAsync sync = new myAsync();
sync.execute();
}
        });}

    }  

和服务器端:

 public class Server {  

    /** 
     * @param args 
     */  
    public static void main(String[] args) throws IOException,EOFException {  
        // TODO Auto-generated method stub  
     FileOutputStream fos;  
     BufferedOutputStream bos;  
     OutputStream output;  
     DataOutputStream dos;  
     int len;  
     int smblen;   
     InputStream in;  
     DataInputStream clientData;  
     BufferedInputStream clientBuff;  


    ServerSocket serverSocket = new ServerSocket(1500);  
    Socket clientSocket = null;  
    clientSocket = serverSocket.accept();  


        in = clientSocket.getInputStream(); //used    

       clientData = new DataInputStream(in); //use    
       clientBuff = new BufferedInputStream(in); //use    
      int N=1;
         while(N==1){    

            System.out.println("Starting...");    

               int fileSize = clientData.read();        
                        fileSize = (fileSize > 0) ? fileSize:0;      


                        List<File> files = new ArrayList<>(fileSize);          
                        List<Integer> sizes = new ArrayList<>(fileSize);

                for (int count=0;count < fileSize;count ++){  

                        sizes.add(clientData.readInt());  
                }  

               for (int count =0;count < fileSize ;count ++){     

                  len=sizes.get(count);  

                System.out.println("File Size ="+len);  

                //output = new FileOutputStream("C:/share/" + fileName);  
                output = new FileOutputStream("D://Users/" + files.get(count));  
                dos=new DataOutputStream(output);  
                bos=new BufferedOutputStream(output);  

                byte[] buffer = new byte[1024];    

                bos.write(buffer, 0, buffer.length); //This line is important  

                while (len > 0 && (smblen = clientData.read(buffer)) > 0) {   
                    dos.write(buffer, 0, smblen);   
                      len = len - smblen;  
                      dos.flush();  
                    }    
            N=2;
              }   
       }  

      } //end loop   

 }  

提前致谢

stacktrace:

 Exception in thread "main" java.lang.IllegalArgumentException: Illegal Capacity: -1
at java.util.ArrayList.<init>(Unknown Source)
at Server.main(Server.java:49)

2 个答案:

答案 0 :(得分:1)

不要将负值传递给ArrayList构造函数。您也可以使用菱形运算符(在Java 7+中),您可能更喜欢使用List接口。所以,像这样 -

int fileSize = clientData.read();
fileSize = (fileSize > 0) ? fileSize : 0;             // guard against negatives.
List<File> files = new ArrayList<>(fileSize);         // Using List and <>
List<Integer> sizes = new ArrayList<>(fileSize);

答案 1 :(得分:0)

你的问题在于以下几点:

int fileSize = clientData.read();  

ArrayList<File>files=new ArrayList<File>(fileSize); //store list of  filename from client directory  
ArrayList<Integer>sizes = new ArrayList<Integer>(fileSize); //store file size from client

read方法在流结束时返回-1。您没有检查这个并尝试将其用作ArrayList的初始容量。添加适当的错误检查 - 你会没事的。