So my main idea is opening a uploaded file in res/raw directory, edit it, save and reopen it. But i also need a function to set default (overwrite csv file with the default one), so i need 2 files, the default one and the other one I edit and read.
Is it true that u can't write a file and store it in res/raw directory? If yes, then what's the best way to do it in this case? Should i save everything in internal/external storage and open later it from here?
try {
FileOutputStream fileOut = openFileOutput("C:\\Users\\textfile.csv", MODE_WORLD_WRITEABLE);
OutputStreamWriter outputWriter = new OutputStreamWriter(fileOut);
for (int b = 0; b < test.AddName("Karlos",1,1,vardadienas).size(); b++) {
outputWriter.write(test.AddName("Karlos",1,1,vardadienas).get(b));
outputWriter.write("\n");
}
outputWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
I use getResources() method and read the file (uploaded in resources folder), save it in a list array, edit the array and then i should save, but where? And also why this method doesnt create any file? I have set the path, but it doesn't create anything..
I also get this error:
at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:201)
at com.example.firstapp.firstapp.MainActivity.onCreate(MainActivity.java:86)
You can't write to res/raw as it is part of the apk file.
But you can read from res/raw ant then write a copy of the file in the app's local and private storage.
Then, whatever you planned to do with the file in res/raw you can do it in the local storage copy.
Related
First I'm writing the excel file in a temporary location then I'm downloading it from that location. Here is the code:
Here I'm writing excel into some temporary location and returning the location of that file:
public String parseExcel(Map<String, List<String>> data) {
Workbook workbook = new XSSFWorkbook();
Sheet sheet1 = workbook.createSheet("Sheet1");
.
.
.
var tmplocation = File.createTempFile("SampleTemplate", ".xlsx");
FileOutputStream fileOut = new FileOutputStream(tmplocation);
workbook.write(fileOut);
fileOut.close();
return tmplocation.getPath();
}
And here I'm downloading that file from that location:
try {
filePath = parseExcel(data);
file = new File(filePath);
return Cors.add(request, Response.ok(file).header("Content-Disposition",
"attachment;filename=\"SampleTemplate.xlsx\"").header("Content-Length ", file.length())).allowAllOrigins().auth().build();
} catch() {
.
.
.
}
To delete the temporary file I added finally block and in finally block I'm getting the file, but it didn't worked. It said FileNotFound Exception
How can I delete this temporary file after the successful download of the file?
The deleteIfExists() method of java.nio.file.Files can help you.
Deletes a file if it exists.
As with the delete(Path) method, an implementation may need to examine the file to determine if the file is a directory. Consequently this method may not be atomic with respect to other file system operations. If the file is a symbolic link, then the symbolic link itself, not the final target of the link, is deleted.
If the file is a directory then the directory must be empty. In some implementations a directory has entries for special files or links that are created when the directory is created. In such implementations a directory is considered empty when only the special entries exist.
On some operating systems it may not be possible to remove a file when it is open and in use by this Java virtual machine or other programs.
You may also wish to use createTempFile() to create your file.
For reference:
Java better way to delete file if exists
Java Tutorials - Deleting a File or Directory
You want to delete a file? You might think of file.delete ();.
You can find that it actually exists by reading the documentation for the File class and scanning the list of methods. In doing so, you will see things that you will remember later on, so it is a great way to expand knowledge.
Documentation is useful.
If you use an IDE like Eclipse, you can get a context-sensitive menu of suggestions, usually a list of possible methods you might use.
I have two datasets which are currently in the same folder as my java files AND on my PC. Currently, I am accessing them through my C-drive. Since this is an app, where should I save my .ARFF files and what path should I use instead? I have tried in the raw folder, but nothing seems to work.
Here's what I have so far...
Create a raw directory in your project, raw is included in the res folder of android project. You can add an assets files in raw folder like music files, database files or text files or some other files which you need to access directly
1) Right click on res folder, select New> Directory, then studio will open a dialog box and it will ask you to enter the name.
2) Enter “raw” and click OK. Open res folder and you will find your raw folder under it.
InputStream input = Context.getResources().openRawResource(R.raw.your_file_name);
// Example to read file from raw directory
private String readFileFromRawDirectory(int resourceId)
{
InputStream iStream = context.getResources().openRawResource(resourceId);
ByteArrayOutputStream byteStream = null;
try {
byte[] buffer = new byte[iStream.available()];
iStream.read(buffer);
byteStream = new ByteArrayOutputStream();
byteStream.write(buffer);
byteStream.close();
iStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return byteStream.toString();
}
}
After too many hours
A very easy solution to retrieving data from the assets folder! Only one user-defined method.
Make raw folder in res directory.
Paste whatever files in the raw directory
Make a separate .java file
Make sure it is a derivative class (in this case it extended AppCompatActivity
Write Part A in the body
Write Part B outside the body
A. This is in the main function OR in a custom, user-defined function.
BufferedReader bReader;
bReader = new BufferedReader(
new InputStreamReader(ISR(R.raw.FILENAME_WITHOUT_TYPE)));
FILENAME_WITHOUT_TYPE refers to only the name of the file, not its ending (everything followed by the .).
B. This is the definition of ISR.
public InputStream ISR(int resourceId) {
InputStream iStream = getBaseContext().getResources().openRawResource(resourceId);
return iStream;
}
Works like a charm!
Resources:
https://inducesmile.com/android-programming/how-to-read-a-file-from-raw-directory-in-android/
https://gist.github.com/Airfixed/799e784696b0a60c5423d347bf33a341
I was able to upload an expandable file and download it
on my app from google play. Following the o[fficial tutorial][1]
It saved the obb file to /Android/Obb/main.2.myappname.obb
I assumed this obb file would be extracted on assets or raw folder or
something similiar. The obb file was renamed after I zipped about 20 .mp3
files. They are named like so: 1.mp3, 2.mp3 etc.
Is it possible to extract the obb file if not how will I be able to
access the invididual mp3 files, the way I am able to access them from
assets or raw folder. Let's say I want to access 1.mp3 which is present
on the .zip archive that was renamed to main.2.myappname.obb
Thank you.
I'm surprised that no one has chimed in here. You can use the StorageManager to mountObb(), unmountObb(), getMountedObbPath(), and isObbMounted(). After mounting an Obb and calling getMOuntedObbPath, you can use the path returned to do normal reads from it. It acts as a virtual drive. You just cannot write back to it.
Here's the link to the documentation: https://developer.android.com/reference/android/os/storage/StorageManager.html
You can read from the OBB directly via an InputStream using the APK Expansion Zip Library. Documentation:
https://developer.android.com/google/play/expansion-files?hl=ko#ZipLib
Sample code:
try {
String obbFilePath = mContext.getObbDir() + "/" + "main.{package_name}.{version_code}.obb";
ZipResourceFile expansionFile = new ZipResourceFile(obbFilePath);
InputStream inputStream = mExpansionFile.getInputStream("1.mp3");
} catch (Exception e) {
Log.d(TAG, "Exception loading obb: " + e);
}
In place of the last line, since you are streaming a MP3, using MediaPlayer is a better idea.
I have a problem checking if a file exists or not this is my simple code:
File myfile = new File ("SecretFile");
if(myfile.exists(){
TextView mytxt = (TextView)findViewById(R.id.textView);
mytxt.setText("Loaded successfully");
}
else{
try {
myfile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
TextView mytxt = (TextView)findViewById(R.id.textView);
mytxt.setText("Not loaded,reboot the application");
}
I am doing a simple game and i need to check the first app run , because when the app runs it load all variables from files but on the first run there's no files so the app crashes.
I also have another question the File "SecretFile" where is located?
How can I create a file inside Android/data/com.mypackage.myapp/SecretFile ?
File myfile = new File ("SecretFile");
That statement has no meaning on Android.
I also have another question the File "SecretFile" where is located?
Nowhere. You are welcome to store your SecretFile on internal storage or external storage, but you must do so by creating a File object pointing to those locations (e.g., File myfile = new File(getFilesDir(), "SecretFile");).
How can I create a file inside Android/data/com.mypackage.myapp/SecretFile ?
You can't. The closest match is to use getExternalFilesDir(null) where I have getFilesDir() in my above code snippet, which would put your file in Android/data/com.mypackage.myapp/files/SecretFile on external storage. Also as Der Golem notes, you would need the WRITE_EXTERNAL_STORAGE permission on API levels 4 through 18.
In creating file in android, you need to add path where you will create file. If you cannot fill its requirement, file will not be created.
That's the reason why ur return data is always false.
This link can help you.
I have created a file stored on internal storage from an activity. How can I delete this file from another activity?
I'm thinking I'll have to get the file's directory (which I'm not sure how to) and delete it. I tried using
context.deleteFile();
but it won't work because I'm trying to call it from a non-static method.
Here is your answer :
File dir = getFilesDir();
File file = new File(dir, "my_filename");
boolean deleted = file.delete();
You can try getting the instance pointing to the file and deleting it like in
this answer
or this one