在java中编写字节数组

时间:2013-11-28 14:17:10

标签: java inputstream outputstream

我正在尝试实现Java服务器/ c客户端,我在java中的put方法有问题。 服务器接收例如数组缓冲区。我在服务器上打印了收到的信息,然后是{-17 -65 -67 -17 -65 -67 -17 -65 -67 -17 -65 -67 0 16 74 70 73 70 0 1 1 0 0 1 0} 。 但是当我用

写它
FileOutputStream out = new FileOutputStream(filename);
out.write(buffer);

然后我用

读取同一个文件
FileInputStream is = new FileInputStream(filename);
is.read(buffer);

我没有得到相同的字节数组。在这个例子中我得到:buffer = {-17 -65 -67 -17 -65 -67 -17 -65 -67 -17 -65 -67 0 16 74 70 73 1 0 0 -1 -2 0 59 67} < / p>

编辑:

private void put(String request, InputStream entreeSocket, OutputStream sortieSocket) {
    //request = "a/b/c/file.txt";
    System.out.println(request);
    String[] s = request.split(" ");
    Path path =  Paths.get(s[0]);
    String filename ="";
    int i = s[0].indexOf('/');
    //System.out.println(request+i);
    if (i != -1){//System.out.println(request.substring(i));
        filename = s[0].substring(s[0].lastIndexOf('/')+1);
        s[0] = s[0].substring(0,s[0].lastIndexOf('/'));
        path = Paths.get(s[0]);
        filename = path + "/"+filename;
        if (Files.notExists(path)){
        if (!new File(s[0]).mkdirs()) return;
        }
        //System.out.println(path + " " + filename);
    }
    else filename = s[0];

    i = request.indexOf("Content-Length");
    //System.out.println(request.substring(i));
    i = request.indexOf(":",i);
    //System.out.println(request.substring(i));
    int j = request.indexOf("\r\n",i);
    int length = Integer.valueOf(request.substring(i+1,j).trim()); 
    //System.out.print(length);
    byte[] buffer = new byte[2048];
    j = request.indexOf("\r\n\r\n");
    request = request.substring(j+4);
    System.out.print(length);
    //length = length - request.length();
    try {
        buffer = request.getBytes("UTF-8");
        print(buffer,buffer.length);
        length -= request.getBytes("UTF-8").length;
        FileOutputStream out = new FileOutputStream(filename);
        out.write(buffer, 0, request.getBytes("UTF-8").length);
        length = 0;
        while(length > 0){
            int nb;
            if(length > buffer.length)
                nb = entreeSocket.read(buffer,0,buffer.length);
            else
                nb = entreeSocket.read(buffer,0,length);
            print(buffer,nb);
            out.write(buffer,0,nb);
            if(nb == -1) break;
            length -=nb;

        }

        sortieSocket.write(new String("205 OK\r\n").getBytes());
        out.close();



        entreeSocket.close();
        sortieSocket.close();


        FileInputStream is = new FileInputStream(filename);
        int nb = is.read(buffer);
        print(buffer,nb);


    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

我的腐败文件的首次亮相:

ef bf bd 50-4e 47 0d 0a-1a 0a 00 00-00 0d 49 48

原始文件的首次亮相

89 50 4e 47-0d 0a 1a 0a-00 00 00 0d-49 48 44 52

0 个答案:

没有答案