我有这个代码从客户端发送文本文件并将其放在服务器端 如何修改此代码使其发送类型为“png”的图像文件而不是发送文本文件..如何为此作业使用字节
在代码中它复制文件内容并将其放入字符串然后再将其写入服务器端的新字符串中 客户端文件有多个文件,您将选择要复制的文本。
这是服务器代码
public static void main(String[] args){
try{
ServerSocket serverSocket = new ServerSocket(2012);
System.out.print("Running");
Socket socket= serverSocket.accept();
System.out.println("Client connected");
PrintWriter pw=new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
String dir = "C:\\Users\\alaqra senpai\\Desktop\\FTP";
File f=new File(dir);
File fl[]=f.listFiles();
Arrays.sort(fl);
int c=0;
for(int i=0;i<fl.length;i++){
if(fl[i].canRead() && (fl[i].toString().endsWith(".txt"))){
c++;
}
}
pw.println(" "+c+".txt file founde , listed A to z");
for (int i=0;i<fl.length;i++){
if((fl[i].toString().endsWith(".txt"))){
pw.println(" "+(i) + " "+ fl[i].getName() + " " +fl[i].length()+"byte");
}
}
pw.println("_");
pw.flush();
String tem=br.readLine();
int temp=Integer.parseInt(tem);
temp-=48;
System.out.println("index " +temp);
boolean files=false;
int index=0;
if(temp>=0 && temp<=fl.length){
files=true;
index=temp;
}else{
files=false;
}
if(files){
try{
File ff=new File(fl[index].getAbsolutePath());
FileReader fr=new FileReader(ff);
BufferedReader brf=new BufferedReader(fr);
String s;
while((s=brf.readLine())!=null){
pw.println(s);
}
pw.flush();
if(brf.readLine()!=null){
System.out.println("File read succeful,closing socket");
}
}catch(IOException e ){
System.err.println("error"+e);
}
}
br.close();
socket.close();
}catch(IOException e){
}
}
这是客户端代码
public static void main(String[] args){
try {
//declaration and initialization client socket
Socket socket = new Socket(InetAddress.getByName("Localhost"), 2012);
//read and write on socket
PrintWriter out = new PrintWriter(socket.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//read from console
BufferedReader bu = new BufferedReader(new InputStreamReader(System.in));
String s;
while ((br.read()) != '_') {
System.out.println(br.readLine());
}
System.out.println("enter file index no: ");
out.println(bu.read());
//force write buffer
out.flush();
//file receive process
try {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("Recevie.png")));
while ((s = br.readLine()) != null) {
bw.write(s);
}
//force write buffer to server
bw.close();
if (br.readLine() == null) {
System.out.println("File Write Successful,Socket closing");
}
} catch (Exception e) {
System.out.println("Error" + e);
}
} catch (IOException ex) {
Logger.getLogger(client.class.getName()).log(Level.SEVERE, null, ex);
}
}
答案 0 :(得分:1)
使用FileInputStream和BufferedInputStream作为图像是二进制文件。在这里查看更多有关使用流的信息 - http://tutorials.jenkov.com/java-io/index.html,很好地解释了java io。