I am trying to build a server program that receives file from client using DataInputStream and BufferedInputStream.
Here's my code and it falls into infinite loop, I think it's because of not using available() but I am not really sure.
DataInputStream din = new DataInputStream(new BufferedInputStream(s.getInputStream()));
//s is socket that connects fine
fos = new FileOutputStream(directory+"/"+filename);
byte b[] = new byte[512];
int readByte = din.read(b);
while(readByte != 1){
fos.write(b);
readByte = din.read(b);
//System.out.println("infinite loop...");
}
Can anyone tell me why it falls into infinite loop? if it is because of not using available , would you please tell me how to use it? I actually googled, but I was confused with the usage. Thank you very much
I think you want to do while(readByte != -1)
. See the documentation (-1 means there is nothing more to read).
This works for me:
FileInputStream in = new FileInputStream(new File("C:\\Users\\Rachel\\Desktop\\Test.txt"));
DataInputStream din = new DataInputStream(new BufferedInputStream(in));
FileOutputStream fos = new FileOutputStream("C:\\Users\\Rachel\\Desktop\\MyOtherFile.txt");
byte b[] = new byte[512];
while(din.read(b) != -1){
fos.write(b);
}
System.out.println("Got out");