黑马程序员技术交流社区
标题:
怎么运行都报错
[打印本页]
作者:
寐海流风
时间:
2014-6-25 20:59
标题:
怎么运行都报错
本帖最后由 寐海流风 于 2014-6-26 09:58 编辑
怎么能实现自动获取文件名和文件扩展名呢?代码如下,请高手检阅!
public class Test9 {
public static void main(String[] args) throws Exception {
TextClient.uploadFile();
}
}
//客户端
class TextClient{
public static void uploadFile(){
Socket socket = null;
FileInputStream fis = null;
OutputStream out = null;
InputStream in = null;
//"D:\\JavaProject\\exam\\34.jpg"
File file = new File("D:\\JavaProject\\exploration&discovery\\abc.jpg");
try{
//"192.168.0.108"
socket = new Socket(InetAddress.getLocalHost(),10033);
fis = new FileInputStream(file);
out = socket.getOutputStream();
String fileName = file.getName();
System.out.println(fileName.toString());
out.write((fileName+"\r").getBytes());
byte[] bufOut = new byte[1024];
int len = 0;
while((len=fis.read(bufOut))!=-1){
out.write(bufOut,0,len);
}
socket.shutdownOutput();
in = socket.getInputStream();
byte[] bufIn = new byte[1024];
int num = in.read(bufIn);
System.out.println(new String(bufIn,0,num));
}catch(UnknownHostException e){
System.out.println("获取本地主机IP地址失败!");
}catch(IOException e){
System.out.println(e.toString());
}finally{
if(fis!=null){
try{
fis.close();
}catch(IOException e){
System.out.println("关闭输入流失败!");
}
}
if(socket!=null){
try{
socket.close();
}catch(IOException e){
System.out.println("关闭套接字流失败!");
}
}
}
}
}
//服务端
class TextServer{
public static void main(String[] args) throws IOException {
@SuppressWarnings("resource")
ServerSocket serverSocket = new ServerSocket(10033);
while(true){
final Socket socket = serverSocket.accept();
new Thread(new Runnable(){
@Override
public void run() {
int count = 1;
InputStream in = null;
FileOutputStream fos = null;
OutputStream out = null;
try{
String ip = socket.getInetAddress().getHostAddress();
System.out.println(ip + "...connected.");
in = socket.getInputStream();
int by = 0,x = 0;
byte[] bytes = new byte[1024];
while((by=in.read())!=13){
bytes[x++] = (byte) by;
}
String fileName = new String(bytes,"GBK");
System.out.println(fileName.toString());
String fileExtension = fileName.substring(fileName.lastIndexOf('.')+1);
System.out.println(fileExtension.toString());
File file = new File(ip+"("+count+")."+fileExtension);
while(file.exists())
file = new File(ip+"("+(count++)+")."+fileExtension);
fos = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len = 0;
while((len=in.read(buf))!=-1){
fos.write(buf,0,len);
}
out = socket.getOutputStream();
out.write("上传成功!".getBytes());
fos.close();
socket.close();
}catch(Exception e){
throw new RuntimeException("文件上传失败!");
}
}
//启动线程
}).start();
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2