【问题标题】:File under data/data/<package_name>/files not showing in my Android Devicedata/data/<package_name>/files 下的文件未显示在我的 Android 设备中
【发布时间】:2021-05-09 02:35:00
【问题描述】:

我正在制作一个应用程序,它将获取服务器日志并将其存储在最终用户的安卓手机中。我正在使用 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();
     }

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

Device File Explorer Snapshot

【问题讨论】:

  • 您将文件存储在应用专用存储中。因此它们是......仅对您的应用程序私有。

标签: android file android-emulator inputstream fileoutputstream


【解决方案1】:

授予访问 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();
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 2012-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-26
    相关资源
    最近更新 更多