I am trying to read from a .txt file located within the project structure. After the app has been compiled to the device (tested on both Android and iOS), I begin by checking if the file exists. It does not seem to.
fileAccess.ts:
import fs = require("file-system");
export class FileAccess
{
public data(filePath: string)
{
let exists = fs.File.exists(filePath);
console.log(exists);
}
}
test.txt (located in same directory as fileAccess.ts):
1;DAC
Calling data("./test.txt"); on an instance of FileAccess, the console prints false.
I assume that either I am referencing the file wrong, or the file is not being copied to the device. But which is it, and how do I fix it?
You could use knownFolders for that. Assuming test.txt is in the root of the app folder:
let appPath = fs.knownFolders.currentApp().path;
let myTextFile = appPath + "/test.txt"
Related
Im making an app for editing system files (data/data folder). I know that app needs root permission. How can I move files from one data/data folder to other. I thought that it would be easier to make when executing bash command.
Also maybe you have some useful info or documentation for building apps with root
I tried this
but.setOnClickListener {
root
var testName = "bruh.txt"
var text = "Help me"
File( filesDir , testName).writeText(text)
var dstString = "/data/data/com.test.testinproj/code_cache/"
var srcString = "/data/data/com.test.testinproj/files/bruh.txt"
Runtime.getRuntime().exec("mv \"$srcString\" \"$dstString\"")
I expected that it will create file called bruh.txt in filesDir, and will move it to directory i need
You can copy files in Kotlin without making an operating system exec call.
File(srcString).copyTo(
target = File(dstString, "bruh.txt")
)
You can also copy files recursively, which may be easier, if you have multiple files to deal with.
If you need to make sure the destination file and directory is writable:
val destFile = File(dst, "bruh.txt").apply {
if (!parentFile.canWrite()) {
throw IOException("cannot write to $parent")
} else if (exists() && !canWrite()) {
throw IOException("cannot write to ${this.absolutePath}")
}
}
File(srcString).copyTo(
target = destFile
)
I am developing a file based application through flutter.
I can create a folder through getApplicationDocumentsDirectory() which gives the path to write files. But it cannot be seen in the files Explorer
I then created the folder through getExternalStorageDirectory() , which can be seen in the files explorer. But I want it to be created in the root.
You may have seen whatsapp folder in the root directory. I also want the same thing. I have tried the following:
Directory('FolderName').create()
But it gives the error saying 'read only os '
Is there a way to do it through flutter ?
You can do it this way:
String folderName = "My New Downloads";
var path = "storage/emulated/0/$folderName";
await new Directory(path).create();
After a lot of googling, and a lot of tries with "out-of-context" code, I'm begging you to help me.
I'm trying to figure out if it's possible to write on the external storage with Nativescript. I'm not interested to write within the application context. So what the docs shows, it's not what i'm looking for.
I've managed to achieve this from a thread on the Nativescript forum:
android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS).toString();
It works, it gives me a path, but when I have this path I have no clue of what to do with it. How to create a file inside that path, read it etc.
What I need to achieve is to create a folder that both the user and the application can easily access. The user should be able to access this folder with the builtin files explorer.
The application runs on Angular.
I really struggled with this one on Android device and in the end it was due to:
Not making sure the required permissions has been granted by the user in the app
Using "Android File Transfer" on my Macbook to verify the files have been created and to download them
tns info
nativescript 6.0.3
tns-core-modules 6.0.7
tns-android 6.0.2
tns plugins
nativescript-permissions 1.3.7
example code
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);
});
android file transfer issue
One problem I wasted a lot of time on was that I could see the files with getEntities() but could not see them when using the 3rd party tool "Android File Transfer (AFT)" on Mac. I eventually stumbled across "Android Studio's -> Device File Explorer" and could see all my created files and folders with it so realised the issue is with AFT.
I now make use of Airdroid to browse and download device files.
applicable reference
https://docs.nativescript.org/angular/ng-framework-modules/file-system
(angular docs but relevant to nativescript-vue as well)
Do you know your external(sd card) path?
If it is like /storage/emulated/0, then you could try this to create a folder or file.
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)
User should be able to access this fold and file. It is in device internal storage which is "external" folder.
I still try to figure out how to get access to sd card but hope above code work for you.
I have the same issue and finally solved it by adding android:requestLegacyExternalStorage="true" inside the AndroidManifest.xml file
follow the thread here
I can't run my python program on my android device using qpython3.
The first step in he program is to create a text file to save data to it. But I get an I/O error (file system read only)
This is the function used to create / or be sure that the file exists easily.
def filecreate(file): # creates the text file
f = open(file, 'a')
print('file created successfully\n')
print()
f.close()
How to overcome this problem in android ?
QPython by default runs your programs from the root directory which is not writable by non-root users. If you check the ftp utility (under About menu) you will find the name of the directory that is writable by QPython. On my HTC it is:
/storage/emulated/0/com.hipipal.qpyplus
So you need to do something along the lines of:
RootPath='/storage/emulated/0/com.hipipal.qpyplus'
...
import os
f = open(file, os.path.join(RootPath,'a'))
...
Example of a similar problem with QPython and SQLite3
Just create the file with QPython before use in your script.
You can create an txt file with QPython.
In My case I create the file whith name "pontoText.txt"
Inside folder "MyPythonScripts" (Im create that folder to put my python files)
so the file is in the same folder of the script and are created in QPython
Now an example code im make ton test:
import time
import os
a = input("1 to save date on file or 2 too see records on file. ")
folder= '/storage/emulated/0/MyPythonScripts'
if(a == "1"):
pontoTxt=open(os.path.join(folder,'pontoText.txt'),'w')
pontoTxt.write(time.strftime("%I %M %p on %A, %B %e, %Y"))
if(a == "2"):
pontoTxt=open(os.path.join(folder,'pontoText.txt'),'r')
exibe = pontoTxt.read()
print(exibe)
Your app may not have required permission to manage that file. Check your manifest, specify Android version and file path. Check documentation: http://developer.android.com/training/basics/data-storage/files.html
You have to actually find the file path, as it doesn't infer the directory that the file is in as the destination directory, unlike in Python on the PC.
Use what they're changed.
The file you have is inside /accounts/mastercard root and the file you're inside is /accounts/main.py you only need to use is this
/mastercard/xxxxx like my code
from django.shortcuts import render
from django.http import HttpResponse
from . import models
# Create your views here.
def index(request):
return render(request,"mastercard/Templates/mastercard/Base.html")
def about(request):
return render(request,"mastercard/Templates/mastercard/index.html")
I am trying to write a file in the internal storage directory of my application with the following step :
1) Initializing my "jni library" in Acivity Class :
MyLib mylib = new MyLib();
2) Give the internal storage path by calling getFilesDir in my Activity Class:
mylib.setSavePath(getFilesDir());
3) Call a method mylib.save() from my library which is doing the following in c++:
Open the file which i want to write with :
fp = fopen(pathtotheinternalstorage+filename,"w");
if (!fp) {
SetError(XML_ERROR_FILE_NOT_FOUND, filename, 0);
return _errorID;
}
The file path is correct : /data/data/com.myapp/files/myfile.xml
But fopen fails, i dont know what i am doing wrong.
If i write with some java code (openFileOutput), it is working well.
Thanks for your help.
More information would be helpful. Based on the path, I'm assuming you're on a Linux box. I would first check the permissions of the path. A few suggestions below
1) Try opening a file in your home directory and see if you have the same issue.
2) Try setting the file world writable using chmod 777 and see if that fixes the problem. Remember setting world writable is really INSECURE and you should change it to something more restrictive once you've found the problem.
I found the answer, i was using a library that was redefinig fopen to read inside asset folder.
#define fopen(name, mode) android_fopen(name, mode)
now it s working