data/data/<package_name>/files 下的文件未显示在我的 Android 设备中

问题描述

我正在制作一个应用程序,它将获取服务器日志并将其存储在最终用户的 Android 手机中。我正在使用 InputStream 和 FileOutputStream 读取和写入文件,它在模拟器的 data/data//files 文件夹下生成一个新的文本文件。但是,当通过 USB 连接时,它没有显示在我的物理 android 设备中。使用以下逻辑:

   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();
     }

有什么办法,我可以在我的手机中查看这个文件而无需 root 并提供一些权限或任何更好的选择?非常感谢你们的投入。

Device File Explorer Snapshot

解决方法

在 AndroidManifest.xml 中授予访问存储的权限,并添加以下逻辑以将数据写入设备存储中的 data/data//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();
            }
        }
    }
}