已二进制方式读取文件并返回给发送者响应的问题(见内)
程序做为一个服务器端接收客户端发过来的消息,然后已二进制形式读取本地的一个文件,然后把读取到的内容响应给客户端.
部分代码:
BufferedReader in = new BufferedReader
(new InputStreamReader(incoming.getInputStream()));
PrintWriter out = new PrintWriter
(incoming.getOutputStream(), true /* autoFlush */);
InputStream br = null;
String line = null;
//读入多个字节到字节数组中,byteread为一次读入的字节数
byte[] tempbytes = new byte[100];
int byteread = 0;
br = new FileInputStream( "e://GetUARet.bin ");
while ((line = in.readLine()) != null) { //收到的消息不为空
while ((byteread = br.read(tempbytes)) != -1){
out.write(tempbytes);
}
问题:1。这种读取文件的方式是否是二进制的形式?
2。怎样才能把读取的内容响应给客户端?out.write(tempbytes)这种写法好像不对
------解决方案--------------------参考....
import java.io.*;
import java.net.*;
import java.util.*;
public class EchoServer {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
ServerSocket ss = new ServerSocket(8189);
Socket incoming = ss.accept();
try {
InputStream is = incoming.getInputStream();
OutputStream os = incoming.getOutputStream();
Scanner in = new Scanner(is);
PrintWriter out = new PrintWriter(os, true);
out.println( "Hello!Enter BYE to exit! ");
boolean done = false;
while (!done && in.hasNextLine()) {
String message = in.nextLine();
Scanner fileIn = new Scanner(new FileReader( "d://1.dat "));
while (fileIn.hasNextLine())
out.println(fileIn.nextLine());
fileIn.close();
if (message.trim().equals( "BYE "))
done = true;
}
} finally {
incoming.close();
}
} catch (
IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}