我正在使用Android Studio构建应用程序,其中客户端从服务器接收图像,在Gallery中创建一个新目录,然后将图像保存在其中。
现在,将创建Gallery中的新文件夹以及 .jpg
文件,但是无法打开该文件。它仅在文件上显示 “!” 标记。以下是我的服务器和客户端的代码:
编辑后,即使在字节数组上执行mBitmap.compress时,我仍然得到NullPointerException,即使它打印出来并且它不为空
//Server
ContentResolver cr = getContentResolver();
try {
InputStream is = cr.openInputStream(uri);
System.out.println("cAME here");
byte[] bytes = new byte[(int)uri.getPath().length()];
is.read(bytes, 0, bytes.length);
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(bytes);
oos.flush();
socket.close();
final String sentMsg = "File sent to: " + socket.getInetAddress();
ServerSocketThread.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(ServerSocketThread.this,
sentMsg,
Toast.LENGTH_LONG).show();
}
});
}
现在是客户端:
//Client
Socket socket = null;
Client.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(Client.this,
"connected",
Toast.LENGTH_LONG).show();
}
});
try {
socket = new Socket(address, portNumber);
File fileDir = new File(Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"LetsShare");
if(fileDir.exists() == false){
fileDir.mkdirs();}
File file = new File(fileDir,"test.jpg");
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
byte[] bytes;
FileOutputStream fos = null;
try {
bytes = (byte[])ois.readObject();
fos = new FileOutputStream(file);
fos.write(bytes);
Client.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(Client.this,
"Finished",
Toast.LENGTH_LONG).show();
}
});
scanMedia(file.toString());
//File toSet = new File(file.toString());
//imageView.setImageBitmap(BitmapFactory.decodeFile(toSet.getAbsolutePath()));
}
}
}
有人可以解释为什么未正确保存图像并且无法打开图像吗?
已编辑的客户端:
socket = new Socket(address, portNumber);
File fileDir = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"LetsShare");
if(fileDir.exists() == false){
fileDir.mkdirs();}
File file = new File(fileDir,"test.jpg");
file.createNewFile();
InputStream is = socket.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
// int length = ois.readInt();
byte[] bytes = new byte[1024];
try{
bytes = (byte[])ois.readObject();}catch (ClassNotFoundException e)
{
}
for (int i=0;i<bytes.length;i++)
{
System.out.println(bytes[i]);
}
FileOutputStream fos = null;
Bitmap myBitmap = BitmapFactory.decodeByteArray(bytes,0,bytes.length);
try {
fos = new FileOutputStream(file);
myBitmap.compress(Bitmap.CompressFormat.JPEG,90,fos);
fos.flush();
fos.close();
Client.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(Client.this,
"Finished",
Toast.LENGTH_LONG).show();
}
});
scanMedia(file.toString());
//File toSet = new File(file.toString());
//imageView.setImageBitmap(BitmapFactory.decodeFile(toSet.getAbsolutePath()));
}