Android cannot write text into resource file - java

I created a raw folder inside res (res/raw) and I also created my_text_file.txt file.
Now I want to write something in this file.
I wrote some code but I cannot write (for example) a simple string.
This is my code.
If anyone knows what is wrong in my code, please help me
try {
FileOutputStream fos = openFileOutput("my_text_file.txt",
Context.MODE_PRIVATE);
OutputStreamWriter osw = new OutputStreamWriter(fos);
osw.write("17");
osw.flush();
osw.close();
} catch (java.io.IOException e) {
// do something if an IOException occurs.
}

You can read your file but not alter the file on the resources folder.
What you can do is to save the file in the external storage then start to alter the file.
Dont forget to set the permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

You shouldn't write to resource files. It exist to store data that you put here before compilation. If you want to save some information in file, during runtime you can do something like this:
public static void writeToFile(String fileName, String encoding, String text) {
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), encoding));
writer.write(text);
} catch (IOException ex) {
Log.e(TAG, "", ex);
} finally {
try {
writer.close();
} catch (Exception ex) {
}
}
}
To find path to SD card you can use this method:
Environment.getExternalStorageState()
So you can use this method like this:
writeToFile(Environment.getExternalStorageState() + "/" + "my_text_file.txt", "UTF-8", "my_text");
And don't forgot to set permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
UPD:
You shouldn't use SD card to store some secure information! More information here.
To write data that will be available only for you application, use this code:
public static void writeToInternalFile(String fileName, String text) {
FileOutputStream fos = openFileOutput(fileName, Context.MODE_PRIVATE);
fos.write(text.getBytes());
fos.close();
}
To read from this file:
public static String readFromInternalFile(String fileName) {
FileInputStream fis = openFileInput(, Context.MODE_PRIVATE);
StringBuilder sb = new StringBuilder();
int ch;
while((ch = fis.read()) != -1){
sb .append((char)ch);
}
return sb.toString();
}

Related

Write to File doesn't persist between activities

I'm writing and reading from a file and it works perfectly fine. However when the activity is switched or the app is closed it appears that the file is deleted or some such as null is returned when trying to read from the file. I believed it may be because I have an onCreate blank write to the file but that should only run upon the launch to make sure the file is created. I don't mind if the file doesn't persist between launches however it should at least persist between activities.
//in oncreate is writeToHistory("");
public void writeToHistory(String toWrite) {
try {
File path = getApplicationContext().getFilesDir();
File file = new File(path, "JWCalcHistory.txt");
FileOutputStream fos = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write(toWrite);
bw.close();
} catch (Exception e){
e.printStackTrace();
}
}
public void btnAnsClicked(View v) throws IOException {
File path = getApplicationContext().getFilesDir();
File file = new File(path,"JWCalcHistory.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String oldAns = br.readLine();
if (!(oldAns.equals("null") || oldAns.equals(""))) {
if (Character.isDigit(readableSum.charAt(readableSum.length() - 1))) {
oldAns = "*" + oldAns;
}
UpdateSum(oldAns);
}
}
If someone can point out a way to make the contents of the file persist always until it is programmatically deleted or cleared then please let me know. The file doesn't already exist and is created upon the code being run.
You need to check if the file exists first. Something like this:
public void writeToHistory(String toWrite) {
try {
File path = getApplicationContext().getFilesDir();
File file = new File(path, "JWCalcHistory.txt");
if(file.exists()) return;
FileOutputStream fos = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write(toWrite);
bw.close();
} catch (Exception e){
e.printStackTrace();
}
}

Unable to write to file - why?

I am attempting to save to long term file storage in android as well as create a new file in the process. This code keeps crashing with minimal helpful logcat.
Thanks.
public void save (String text) {
FileOutputStream fos = null;
try {
fos = openFileOutput("logfile.txt", MODE_PRIVATE);
fos.write(text.getBytes());
} catch (FileNotFoundException e)
{} catch (IOException e) {
e.printStackTrace();
} finally {
if(fos != null)
{
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I expect it to create a file called logfile.txt and print text to it but instead it crashes.
Try something alike this, in order to get a FileOutputStream from a File in tmp / private storage:
// File file = File.createTempFile("logfile", ".txt");
File file = new File(getFilesDir(), "logfile.txt");
FileOutputStream fos = new FileOutputStream(file);
The resulting path should be /data/data/tld.domain.package/files/logfile.txt.
file.getAbsolutePath() has the value.
See Save a file on internal storage.

Android Java Read and Save data doesnt work

Hey I would like to save datas and then I would like to read them and put them in a EditText
speichern.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
save();
tv.setText("gespeichert");
}
});
private void save() {
try {
File myFile = new File("bla.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(string.toString() + "\n");
myOutWriter.append(string2.toString());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Gespeichert",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
private void read() {
int bla;
StringBuffer strInhalt = new StringBuffer("");
try {
FileInputStream in = openFileInput("bla.txt");
while( (bla = in.read()) != -1)
strInhalt.append((char)bla);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
What can i change?`
pelase help me
I'm usin eclipse
And i would like to safe the .txt not external.
I don't believe you are creating your file correctly:
File file = new File("test.txt");
file.createNewFile();
if(file.exists())
{
OutputStream fo = new FileOutputStream(file);
fo.write("Hello World");
fo.close();
System.out.println("file created: "+file);
url = upload.upload(file);
}
And to read this file:
try {
// open the file for reading
InputStream instream = openFileInput("test.txt");
// if file the available for reading
if (instream) {
// prepare the file for reading
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
// read every line of the file into the line-variable, on line at the time
while (( line = buffreader.readLine())) {
// do something with the settings from the file
}
}
// close the file again
instream.close();
} catch (java.io.FileNotFoundException e) {
// do something if the myfilename.txt does not exits
}
And don't forget to encapsulate code with a try-catch block to catch an IOException which is thrown from these objects.
EDIT
Add this to your manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
or...
File filesDir = getFilesDir();
Scanner input = new Scanner(new File(filesDir, filename));
Hope that helps! :)

Downloading files(.zip, .jar,...) to a folder

I have been trying many ways of downloading a file from a URL and putting it in a folder.
public static void saveFile(String fileName,String fileUrl) throws MalformedURLException, IOException {
FileUtils.copyURLToFile(new URL(fileUrl), new File(fileName));
}
boolean success = (new File("File")).mkdirs();
if (!success) {
Status.setText("Failed");
}
try {
saveFile("DownloadedFileName", "ADirectDownloadLinkForAFile");
} catch (MalformedURLException ex) {
Status.setText("MalformedURLException");
Logger.getLogger(DownloadFile.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Status.setText("IOException Error");
Logger.getLogger(DownloadFile.class.getName()).log(Level.SEVERE, null, ex);
}
I found this code on the net, am i using it correctly?
If i did:
saveFile("FolderName", "ADirectDownloadLinkForAFile")
I would get IOException error
What I want my code to do is:
Create folder
Download file
Downloaded file to go to the just created folder
I'm a newbie here sorry. Please help
There are various ways in java to download a file from the internet.
The easiest one is to use a buffer and a stream:
File theDir = new File("new folder");
// if the directory does not exist, create it
if (!theDir.exists())
{
System.out.println("creating directory: " + directoryName);
boolean result = theDir.mkdir();
if(result){
System.out.println("DIR created");
}
}
FileOutputStream out = new FileOutputStream(new File(theDir.getAbsolutePath() +"filename"));
BufferedInputStream in = new BufferedInputStream(new URL("URLtoYourFIle").openStream());
byte data[] = new byte[1024];
int count;
while((count = in.read(data,0,1024)) != -1)
{
out.write(data, 0, count);
}
Just the basic concept. Dont forget the close the streams ;)
The File.mkdirs() statement appears to be creating a folder called Files, but the saveFile() method doesn't appear to be using this, and simply saving the file in the current directory.

Writing file in external storage crashes android app

I know of cours that here were some question about this, but I still can't find answer.
I need to write some text in external storage, but this code makes application crashed. Note that String dane is this text.
void zapis2 (String dane){
Context myContext = getApplicationContext();
File file = new File(myContext.getExternalFilesDir(null), "state.txt");
try {
FileOutputStream os = new FileOutputStream(file, true);
OutputStreamWriter out = new OutputStreamWriter(os);
out.write(dane);
out.close();}catch (IOException e) {
}
}
Have you got any idea. I add permision in android manifest of course.
Try this:
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/foldername");
dir.mkdirs();
File file = new File(dir, "filename.txt");
try {
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println(dane); //your string which you want to store
pw.flush();
pw.close();
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Hope this helps!
Contect.getExternalFilesDir(..) is only available from API8, if you run/deploy on earler versions it will crash.

Categories

Resources