英文:
Why Isn't My FileOutputstream Writing to a File?
问题
我是一个初学者,正在开发一个使用gcacace SignaturePad库来捕获用户签名的Android应用程序。我的目标是将签名压缩为JPEG格式,然后将该信息写入用户手机上的文件,以便以后可以访问该图片。
我目前在运行代码时没有收到任何错误或崩溃,但在我在我的设备上(Google Pixel 2)测试应用程序时没有创建任何目录或文件。有人能帮我找出问题出在哪里吗?整个早上我一直在努力解决问题,但还是毫无头绪。
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("images", Context.MODE_PRIVATE);
if (!directory.exists()) {
directory.mkdirs();
}
File myPath = new File(directory, "1.jpg");
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(myPath);
} catch (Exception e) {
e.printStackTrace();
}
signaturePad.getSignatureBitmap().compress(Bitmap.CompressFormat.JPEG, 90, fOut);
Bitmap signature = signaturePad.getSignatureBitmap();
int bytes = signature.getByteCount();
try {
fOut.write(bytes);
fOut.flush();
fOut.close();
} catch (IOException ex) {
ex.printStackTrace();
}
Toast.makeText(activity_signature_pad.this, "Signature Saved", Toast.LENGTH_SHORT).show();
英文:
I'm a beginner working on an Android app that uses the gcacace SignaturePad library to capture the signature of my user. My goal is to take the signature, compress it down into a JPEG, and then write that information to a file on the users phone so the picture can be accessed later.
I am currently getting no errors or crashes when I run the code, yet no directory or file is being created when I test the app out on my device(Google Pixel 2). Can anyone give me a hand figuring out where the problem is? I've thrown my head against a wall this entire morning and still don't know.
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("images", Context.MODE_PRIVATE);
if (!directory.exists()) {
directory.mkdirs();
}
File myPath = new File(directory, "1.jpg");
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(myPath);
} catch (Exception e) {
e.printStackTrace();
}
signaturePad.getSignatureBitmap().compress(Bitmap.CompressFormat.JPEG, 90, fOut);
Bitmap signature = signaturePad.getSignatureBitmap();
int bytes = signature.getByteCount();
try {
fOut.write(bytes);
fOut.flush();
fOut.close();
} catch (IOException ex) {
ex.printStackTrace();
}
Toast.makeText(activity_signature_pad.this, "Signature Saved", Toast.LENGTH_SHORT).show();
答案1
得分: 0
以下是翻译好的内容:
你提问中的代码部分涉及Android SDK所称的内部存储。这是您的应用程序专用的;普通用户无法访问它(包括您,除非使用开发者工具)。
您似乎想要写入外部存储。为此,请使用:
File directory = new File(getExternalFilesDir(null), "images")
英文:
The code in your question writes to what the Android SDK refers to internal storage. That is private to your app; ordinary users do not have access to it (including you, except when using developer tools).
You appear to want to write to external storage. For that, use:
File directory = new File(getExternalFilesDir(null), "images")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论