Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/187.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android Nativescript:如何在外部存储器(SD卡)中保存文件_Android_Nativescript_Sd Card - Fatal编程技术网

Android Nativescript:如何在外部存储器(SD卡)中保存文件

Android Nativescript:如何在外部存储器(SD卡)中保存文件,android,nativescript,sd-card,Android,Nativescript,Sd Card,在谷歌搜索了很多次,并尝试了很多“断章取义”的代码之后,我请求你帮助我 我试图弄清楚是否可以使用Nativescript在外部存储器上进行写入。我对在应用程序上下文中编写不感兴趣。所以这些文件显示的不是我想要的 我已经通过Nativescript论坛上的一个线程实现了这一点: android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_下载).toString() 它起作用了,

在谷歌搜索了很多次,并尝试了很多“断章取义”的代码之后,我请求你帮助我

我试图弄清楚是否可以使用Nativescript在外部存储器上进行写入。我对在应用程序上下文中编写不感兴趣。所以这些文件显示的不是我想要的

我已经通过Nativescript论坛上的一个线程实现了这一点:

android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_下载).toString()

它起作用了,它给了我一条路,但当我有了这条路,我就不知道该怎么办了。如何在该路径内创建文件、读取文件等

我需要实现的是创建一个用户和应用程序都可以轻松访问的文件夹。用户应该能够使用内置文件资源管理器访问此文件夹

应用程序以角度运行。

您知道外部(sd卡)路径吗? 如果类似于/storage/emulated/0,则可以尝试创建文件夹或文件

import * as fs from "tns-core-modules/file-system";

  let externalPath= fs.path.join(android.os.Environment.getExternalStorageDirectory().getAbsolutePath().toString());
  //Create a folder with known path
  var folder: fs.Folder = fs.Folder.fromPath(sdCardPath+"/test");
  //Create a file 
  var testFile: fs.File = folder.getFile("test.txt");
  console.log("Path " + folder.path)
用户应该能够访问此文件夹和文件。它位于设备内部存储器中,即“外部”文件夹


我仍在尝试如何访问sd卡,但希望上面的代码对您有用。

我在Android设备上遇到了这个问题,最终是因为:

  • 不确保应用程序中的用户已授予所需的权限
  • 在我的Macbook上使用“Android文件传输”来验证文件是否已创建并下载
  • tns信息

    nativescript 6.0.3
    tns-core-modules 6.0.7
    tns-android 6.0.2 
    
    tns插件

    nativescript-permissions 1.3.7
    
    示例代码

            import * as fs from "tns-core-modules/file-system"
    
            ...
    
            // First get the required permissions
            // Note: this permissions should also be in your AndroidManifest.xml file as:
            //   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
            const permissions = require('nativescript-permissions')
            permissions.requestPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
            .then(() => {
                console.log('Required Android permissions have been granted');
            })
            .catch(() => {
                console.error('Required Android permissions have been denied!');
            });
    
            // Get the publicly accessable Downloads directory path
            const sdDownloadPath = android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS).toString()
            console.log('sdDownloadPath: ' + sdDownloadPath)
    
            // Get a specific folder in that path (will be created if it does not exist)
            const myAppFolder = fs.Folder.fromPath(fs.path.join(sdDownloadPath, 'myApp'))
            console.log('myApp path: ' + myAppFolder.path)
    
            // Get a file in that path (will be created if it does not exist)
            // Note: In this case we try to get a unique file every time this code is run
            let date = new Date()
            date = date.toISOString().replace('.', '')
            const myFile = myAppFolder.getFile(`myfile_${date}.txt`) 
            console.log('myFile path: ' + myFile.path)
    
            // Write some data to this new file
            myFile.writeText('Hello duder 123')
            .then(() => {})
            .catch((err) => console.log(`Error writing to file: ${err}`))
    
            // Try and read back the data that was written
            myFile.readText()
            .then((res) => {
                console.log(`Text read back: ${res}`)
            }).catch((err) => {
                console.log(err.stack);
            });
    
            // List all files in the myApp folder
            myAppFolder.getEntities()
            .then((entities) => {
                // entities is array with the document's files and folders.
                entities.forEach((entity) => {
                    console.log(entity)
                });
            }).catch((err) => {
                console.log(err.stack);
            });
    
    import*作为fs从“tns核心模块/文件系统”
    ...
    //首先获取所需的权限
    //注意:此权限也应位于AndroidManifest.xml文件中,如下所示:
    //   
    const permissions=require('nativescript-permissions')
    permissions.requestPermission(android.Manifest.permission.WRITE\u外部存储)
    .然后(()=>{
    log('已授予所需的Android权限');
    })
    .catch(()=>{
    错误('所需的Android权限已被拒绝!');
    });
    //获取可公开访问的下载目录路径
    const sdDownloadPath=android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY\u DOWNLOADS).toString()
    console.log('sdDownloadPath:'+sdDownloadPath)
    //获取该路径中的特定文件夹(如果不存在,将创建该文件夹)
    const myAppFolder=fs.Folder.fromPath(fs.path.join(sdDownloadPath,'myApp'))
    console.log('myApp路径:'+myAppFolder.path)
    //获取该路径中的文件(如果不存在,将创建该文件)
    //注意:在这种情况下,每次运行此代码时,我们都会尝试获取一个唯一的文件
    let date=新日期()
    日期=日期.toISOString()。替换('.','')
    const myFile=myAppFolder.getFile(`myFile{date}.txt`)
    console.log('myFile路径:'+myFile.path)
    //将一些数据写入此新文件
    myFile.writeText('Hello duder 123')
    .然后(()=>{})
    .catch((err)=>console.log(`写入文件时出错:${err}`))
    //试着读回写入的数据
    myFile.readText()文件
    。然后((res)=>{
    log(`Text read back:${res}`)
    }).catch((错误)=>{
    console.log(err.stack);
    });
    //列出myApp文件夹中的所有文件
    myAppFolder.getEntities()
    。然后((实体)=>{
    //实体是文档文件和文件夹的数组。
    实体。forEach((实体)=>{
    console.log(实体)
    });
    }).catch((错误)=>{
    console.log(err.stack);
    });
    
    android文件传输问题

            import * as fs from "tns-core-modules/file-system"
    
            ...
    
            // First get the required permissions
            // Note: this permissions should also be in your AndroidManifest.xml file as:
            //   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
            const permissions = require('nativescript-permissions')
            permissions.requestPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
            .then(() => {
                console.log('Required Android permissions have been granted');
            })
            .catch(() => {
                console.error('Required Android permissions have been denied!');
            });
    
            // Get the publicly accessable Downloads directory path
            const sdDownloadPath = android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS).toString()
            console.log('sdDownloadPath: ' + sdDownloadPath)
    
            // Get a specific folder in that path (will be created if it does not exist)
            const myAppFolder = fs.Folder.fromPath(fs.path.join(sdDownloadPath, 'myApp'))
            console.log('myApp path: ' + myAppFolder.path)
    
            // Get a file in that path (will be created if it does not exist)
            // Note: In this case we try to get a unique file every time this code is run
            let date = new Date()
            date = date.toISOString().replace('.', '')
            const myFile = myAppFolder.getFile(`myfile_${date}.txt`) 
            console.log('myFile path: ' + myFile.path)
    
            // Write some data to this new file
            myFile.writeText('Hello duder 123')
            .then(() => {})
            .catch((err) => console.log(`Error writing to file: ${err}`))
    
            // Try and read back the data that was written
            myFile.readText()
            .then((res) => {
                console.log(`Text read back: ${res}`)
            }).catch((err) => {
                console.log(err.stack);
            });
    
            // List all files in the myApp folder
            myAppFolder.getEntities()
            .then((entities) => {
                // entities is array with the document's files and folders.
                entities.forEach((entity) => {
                    console.log(entity)
                });
            }).catch((err) => {
                console.log(err.stack);
            });
    
    我浪费了很多时间的一个问题是,我可以通过
    getEntities()
    查看文件,但在Mac上使用第三方工具“Android文件传输(AFT)”时无法查看它们。我最终偶然发现了“Android Studio的->设备文件浏览器”,可以看到我创建的所有文件和文件夹,因此意识到问题在于AFT

    我现在利用浏览和下载设备文件

    适用参考

            import * as fs from "tns-core-modules/file-system"
    
            ...
    
            // First get the required permissions
            // Note: this permissions should also be in your AndroidManifest.xml file as:
            //   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
            const permissions = require('nativescript-permissions')
            permissions.requestPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
            .then(() => {
                console.log('Required Android permissions have been granted');
            })
            .catch(() => {
                console.error('Required Android permissions have been denied!');
            });
    
            // Get the publicly accessable Downloads directory path
            const sdDownloadPath = android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS).toString()
            console.log('sdDownloadPath: ' + sdDownloadPath)
    
            // Get a specific folder in that path (will be created if it does not exist)
            const myAppFolder = fs.Folder.fromPath(fs.path.join(sdDownloadPath, 'myApp'))
            console.log('myApp path: ' + myAppFolder.path)
    
            // Get a file in that path (will be created if it does not exist)
            // Note: In this case we try to get a unique file every time this code is run
            let date = new Date()
            date = date.toISOString().replace('.', '')
            const myFile = myAppFolder.getFile(`myfile_${date}.txt`) 
            console.log('myFile path: ' + myFile.path)
    
            // Write some data to this new file
            myFile.writeText('Hello duder 123')
            .then(() => {})
            .catch((err) => console.log(`Error writing to file: ${err}`))
    
            // Try and read back the data that was written
            myFile.readText()
            .then((res) => {
                console.log(`Text read back: ${res}`)
            }).catch((err) => {
                console.log(err.stack);
            });
    
            // List all files in the myApp folder
            myAppFolder.getEntities()
            .then((entities) => {
                // entities is array with the document's files and folders.
                entities.forEach((entity) => {
                    console.log(entity)
                });
            }).catch((err) => {
                console.log(err.stack);
            });
    

    (角度文档,但也与nativescript vue相关)

    我有同样的问题,最后通过在AndroidManifest.xml文件中添加
    android:requestLegacyExternalStorage=“true”
    解决了这个问题 按照线程进行操作

    尝试以下操作: