SD卡中有encrypt.png文件
在E盘可以看到,从模拟器SD卡中发送来的文件
服务器端代码,我这里是使用CMD命令演示的。服务端等待客户端连接,然后接收客户端的数据。包括文件名,大小,和文件数据。
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class FileServer {
private int port = 8821;
private ServerSocket ss;
private Socket socket;
/** 数据输入流,读取来自网络的数据流 **/
private DataInputStream dis;
/** 数据输出流,将来自网络的数据流写入文件 **/
private DataOutputStream dos;
private String savePath = "E:\\";
public void startServer() {
// 已经传输的文件大小
int passedlength = 0;
// 文件总大小
long length = 0;
// 缓存大小
int bufferSize = 8192;
// 缓存
byte[] buf = new byte[bufferSize];
try {
ss = new ServerSocket(port);
socket = ss.accept();
dis = new DataInputStream(new BufferedInputStream(
socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
try {
// 将文件名字读取进来
savePath += dis.readUTF();
// 文件的长度读取进来(实际只是为了显示进度)
length = dis.readLong();
} catch (IOException e) {
e.printStackTrace();
}
try {
dos = new DataOutputStream(new BufferedOutputStream(
new FileOutputStream(savePath)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (true) {
int read = 0;
if (dis != null) {
try {
read = dis.read(buf);
} catch (IOException e) {
e.printStackTrace();
}
}
passedlength += read;
if (read == -1) {
break;
}
// 下面进度条本为图形界面的prograssBar做的,这里如果是打文件,可能会重复打印出一些相同的百分比
System.out.println("文件接收了" + (passedlength * 100 / length) + "%\n");
try {
dos.write(buf, 0, read);
} catch (IOException e) {
e.printStackTrace();
}
}
if (dos != null) {
try {
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
dos = null;
}
if (dis != null) {
try {
dis.close();
} catch (IOException e) {
e.printStackTrace();
}
dis = null;
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
socket = null;
}
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
ss = null;
}
System.out.println("接收完成,文件存为" + savePath + "\n");
}
public static void main(String[] args) {
FileServer fileServer = new FileServer();
fileServer.startServer();
}
}
Android端代码(客户端) 还是要记住在Manifest中添加网络访问权限
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:gravity="center"
android:text="文件上传测试" />
<Button
android:id="@+id/myButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="开始上传" />
</LinearLayout>
文件操作类,主要是使用了里面的获取SD路径的函数
package com.zeph.android.fileclient;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import android.content.Context;
import android.os.Environment;
public class FileHelper {
private Context context;
/** SD卡是否存在 **/
private boolean hasSD = false;
/** SD卡的路径 **/
private String SDPATH;
/** 当前程序包的路径 **/
private String FILESPATH;
public FileHelper(Context context) {
this.context = context;
hasSD = Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED);
SDPATH = Environment.getExternalStorageDirectory().getPath();
FILESPATH = this.context.getFilesDir().getPath();
}
/**
* 在SD卡上创建文件
*
* @throws IOException
*/
public File createSDFile(String fileName) throws IOException {
File file = new File(SDPATH + "//" + fileName);
if (!file.exists()) {
file.createNewFile();
}
return file;
}
/**
* 删除SD卡上的文件
*
* @param fileName
*/
public boolean deleteSDFile(String fileName) {
File file = new File(SDPATH + "//" + fileName);
if (file == null || !file.exists() || file.isDirectory())
return false;
return file.delete();
}
/**
* 读取SD卡中文本文件
*
* @param fileName
* @return
*/
public String readSDFile(String fileName) {
StringBuffer sb = new StringBuffer();
File file = new File(SDPATH + "//" + fileName);
try {
FileInputStream fis = new FileInputStream(file);
int c;
while ((c = fis.read()) != -1) {
sb.append((char) c);
}
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
public String getFILESPATH() {
return FILESPATH;
}
public String getSDPATH() {
return SDPATH;
}
public boolean hasSD() {
return hasSD;
}
}
Activity类,里面的startClient函数完成文件传输到服务器 注意代码里面IP地址填写你自己的。
package com.zeph.android.fileclient;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class FileClientActivity extends Activity {
private Socket socket;
// 这里填写你的IP地址
private String ip = "192.168.0.1";
private int port = 8821;
private DataInputStream dis;
private DataOutputStream dos;
private Button myButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myButton = (Button) findViewById(R.id.myButton);
myButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
new Thread() {
public void run() {
startClient("encrypt.png");
}
}.start();
}
});
}
public void startClient(String fileName) {
FileHelper helper = new FileHelper(getApplicationContext());
String filePath = helper.getSDPATH() + "//" + fileName;
File file = new File(filePath);
try {
socket = new Socket(ip, port);
dis = new DataInputStream(new BufferedInputStream(
new FileInputStream(filePath)));
dos = new DataOutputStream(socket.getOutputStream());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
dos.writeUTF(file.getName());
dos.flush();
dos.writeLong((long) file.length());
dos.flush();
} catch (IOException e) {
e.printStackTrace();
}
int bufferSize = 8192;
byte[] buf = new byte[bufferSize];
while (true) {
int read = 0;
if (dis != null) {
try {
read = dis.read(buf);
} catch (IOException e) {
e.printStackTrace();
}
}
if (read == -1) {
break;
}
try {
dos.write(buf, 0, read);
dos.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
dis.close();
dos.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}