Issue
I am making an app that will fetch the server logs and store it in end-users android phone. I am reading and writing the file using InputStream and FileOutputStream which generates a new text file under data/data/<package_name>/files folder of Emulator. However, it is not showing in my physical android device when connected through USB. Used below logic:
try{
Session session = new JSch().getSession(user, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
InputStream inputStream = sftpChannel.get(remoteFile);
try (Scanner scanner = new Scanner(new InputStreamReader(inputStream))) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
logs.append(line);
}
try {
FileOutputStream fos = null;
fos = openFileOutput(FILE_NAME, MODE_PRIVATE);
fos.write(logs.getBytes());
Toast.makeText(this, "File Saved", Toast.LENGTH_SHORT).show();
}
catch(FileNotFoundException e){
e.printStackTrace();
}
catch (JSchException | SftpException e) {
e.printStackTrace();
}
Is there any way, I could view this file in my phone without rooting and giving some permissions or any better alternative? Highly appreciate your inputs guys.
Solution
Give permissions to access Storage in AndroidManifest.xml and add below logic for writing data to your device storage at data/data/<package_name>/files :
String dirPath = FILE_PATH;
File dir = new File(dirPath);
if (!dir.exists()) {
dir.mkdirs();
}
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(getExternalFilesDir(FILE_PATH), filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
Toast.makeText(this, "File Written to your Storage!", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Failed!", Toast.LENGTH_SHORT).show();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Answered By - Avneet Singh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.