我在assets文件夹中有一个文件。我想打开文件,通过InputStream
读取字节[],然后使用FileOutputStream
将字节[]写入另一个文件。
assetManager = MainActivity.this.getAssets();
assetStream = assetManager.open("qamaster2.pfx");
File file = StringGenerator.createFileFromInputStream(assetStream, "qamaster2.pfx");
和createFileFromInputStream方法:
public static File createFileFromInputStream(InputStream inputStream, String fileName) {
try{
File file = new File(fileName);
Log.e("File", file.getName());
if (file.exists()){
int size = inputStream.available();
Log.e("File size", String.valueOf(size));
byte[] buffer = new byte[size];
inputStream.read(buffer);
inputStream.close();
}
return file;
}catch (IOException e) {
Log.e("Exception", "Something happened here");
e.printStackTrace();
}
return null;
}
但是什么也没发生。有什么建议吗?
像这样从资源中读取文件
try {
InputStream is = context.getAssets().open("file name");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
} catch (Exception ex) {
ex.printStackTrace();
}
然后创建一个新文件,并将这个InputStream写入该文件。
在manifest文件中赋予读写权限。
像这样将输入流写入文件------
try {
InputStream inputStream = null;
OutputStream output = null;
try {
inputStream = getContentResolver().openInputStream(data.getData());
File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES),
"picture_G.jpg");
output = new FileOutputStream(file);
byte[] buffer = new byte[4 * 1024]; // or other buffer size
int read;
while ((read = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
output.flush();
} finally {
inputStream.close();
output.close();
}
} catch (Exception e) {
e.printStackTrace(); // handle exception, define IOException and others
}
在这种情况下,你还可以在本地应用程序文件空间中创建和写入文件,如下所示(改编自之前的回答):
private File createFileFromInputStream(InputStream inputStream) {
try{
File f = new File(getFilesDir(), "temp1.txt");
OutputStream outputStream = new FileOutputStream(f);
byte buffer[] = new byte[1024];
int length = 0;
while((length=inputStream.read(buffer)) > 0) {
outputStream.write(buffer,0,length);
}
outputStream.close();
inputStream.close();
return f;
}
catch (IOException e) { e.printStackTrace(); }
return null;
}