Editing a file using FileWriter - java

I am trying to Edit a existing file which is in my R.raw folder
i am able to read the file
but when i run the write function it is not working .
public void tofile(View v){
BufferedWriter bw=null;
FileWriter fw =null;
try {
String path = ("/Page2/res/raw/text.txt");
File file = new File(path);
fw = new FileWriter(file);
bw = new BufferedWriter(fw);
bw.write("hello");
bw.flush();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
i even tried
fw = new FileWriter(file,true);
if i add toast between even line it seems to get stuck at
fw = new FileWriter(fw);

You can't able to Write
As #CommonsWare said you can't write on resources but you could use internal storage using openFileOutput and openFileInput and BufferedReaders and BufferedWriters. You can check it here
from the answer of #rodkarom in the following link
Write to a Text File Resource in Android
and #Andro Selva says same thing in the following link
How to write a file in Android to the raw folder?
you can able to read the content from the textfile which is present in the res/raw folder dude
read the file from res folder
public String readStringFromResource(Context ctx, int resourceID) {
StringBuilder contents = new StringBuilder();
String sep = System.getProperty("line.separator");
try {
InputStream is = ctx.getResources().openRawResource(R.raw.trails);
BufferedReader input = new BufferedReader(new InputStreamReader(is), 1024*8);
try {
String line = null;
while (( line = input.readLine()) != null){
contents.append(line);
contents.append(sep);
}
}
finally {
input.close();
}
}
catch (FileNotFoundException ex) {
Log.e(TAG, "Couldn't find the file " + resourceID + " " + ex);
return null;
}
catch (IOException ex){
Log.e(TAG, "Error reading file " + resourceID + " " + ex);
return null;
}
return contents.toString();
}
check it and inform

Related

Can not read any text file

First of all, I would like you to say that I am quite new here and I'm also a beginner in Android Studio and Java.
My problem/question is:
I have an App in Android Studio which should write a string to a text file at a specific point and also should read the same file on App startup.
Writing to the file is working but not reading. When I create a text file manually, and insert it manually to the folder it reads the string.
I already added permissions and try to find my error with LogCat but I have no clue at the moment what could be wrong.
Variables:
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/myApp");
My reading function:
String myData = "";
try {
FileReader fileIn = new FileReader(dir + "/data.txt");
Scanner input = new Scanner(fileIn);
while (input.hasNextLine()) {
String line = input.nextLine();
myData = myData + line;
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
}
My writing function:
try {
File file = new File(dir, "data.txt");
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println("answer42");
pw.flush();
pw.close();
f.close();
} catch (Exception ex) {
ex.printStackTrace();
}

Why can't I neither delete nor rename the file?

While creating a method to my class, I got an unexpected problem. I've tried solutions from other theards, but they just don't work for me. My method should simply find the line specified, copy the file skipping unnecessary line, delete the original file and rename temporary file to the name of original file. It succesfuly creates new file as expected, but then fails to delete previous one as it fails to rename temporary file to original. I can't figure out, why?
void lineDelete(String file_name, String line_to_erase){
try {
int line_number = 0;
String newline = System.getProperty("line.separator");
File temp = new File("temporary.txt");
File theFile = new File(file_name+".txt");
String path = theFile.getCanonicalPath();
File filePath = new File(path);
BufferedReader reader = new BufferedReader(new FileReader(file_name + ".txt"));
BufferedWriter writer = new BufferedWriter(new FileWriter(temp));
String lineToRemove = line_to_erase;
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)){
continue;
}
writer.write(currentLine + newline));
}
writer.close();
reader.close();
filePath.delete();
temp.renameTo(theFile);
}
catch (FileNotFoundException e){
System.out.println(e);
}
catch (IOException e){
System.out.println(e);
}
Try this code:
void lineDelete(String file_name, String line_to_erase){
try {
int line_number = 0;
String newline = System.getProperty("line.separator");
File temp = new File("temporary.txt");
File theFile = new File(file_name+".txt");
String path = theFile.getCanonicalPath();
BufferedReader reader = new BufferedReader(new FileReader(theFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(temp));
String lineToRemove = line_to_erase;
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)){
continue;
}
writer.write(currentLine + newline));
}
writer.close();
reader.close();
theFile.delete();
temp.renameTo(file_name + ".txt");
}
catch (FileNotFoundException e){
System.out.println(e);
}
catch (IOException e){
System.out.println(e);
}
I could suggest a couple of reasons why the delete and/or rename might fail, but there is a better way to solve your problem than guessing1.
If you use Path and the Files.delete(Path) and Files.move(Path, Path, CopyOption...) methods, they will throw exceptions if the operations fail. The exception name and message should give you clues as to what is actually going wrong.
The javadoc is here and here.
1 - Here are a couple of guesses: 1) the file has been opened elsewhere, and it is locked as a result. 2) You don't have access to delete the file.

Android adding multiple lines to file internal stroage

I have a simple game app that has 3 place scoreboard and I need to save the data. I'm not sure whether I should be saving this on external or internal storage. I have managed to save a csv file in external but when testing I found it deosnt work on all devices. I am now looking at saving the data on internal storage and looking at the following standard file saving code.
String FILE_NAME = "file.txt";
try {
FileOutputStream fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
fos.write(someText.toString().getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
The class doesnt provide any nextLine() method.
My question is should I use external or internal storage, and if im using internal storage how can I seperate each line?
Writing:
String FILE_NAME = "file.txt";
try {
FileOutputStream fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
PrintWriter writer = new PrintWriter( new OutputStreamWriter( fos ) );
writer.println(someText.toString());
writer.println(someOtherText.toString());
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
Reading:
String FILE_NAME = "file.txt";
try {
FileInputStream fis = openFileInput(FILE_NAME, Context.MODE_PRIVATE);
BufferedReader reader = new BufferedReader( new InputStreamReader( fis ) );
String line;
while ( (line = reader.readLine()) != null ) {
System.out.println("Read line: " + line);
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}

How to copy a text file, and print out the original and copied file in Java

I'm doing a program that needs to take a text file (test.txt) and make a copy of it and print it out. So far I am only able to print out the original file. I have searched for a way of doing this but there doesn't seem to be any help that I can understand, I am very new to java. I am at least looking for guidance, not just the full answer.
my code so far...
import java.io.*;
public class Copy{
public static void main(String [] args){
try{
FileInputStream fis = new FileInputStream("test.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
File a = new File("test.txt");
FileReader fr = new FileReader(a);
File b = new File("Copied.txt");
FileWriter fw = new FileWriter(b);
while(true){
String line = br.readLine();
if(line != null){
System.out.println(line);
} else{
br.close();
break;
}
}
} catch(FileNotFoundException e){
System.out.println("Error: " + e.getMessage());
} catch(IOException e){
System.out.println("Error: " + e.getMessage());
}
}
}
Again any bit of help will be greatly appreciated since I am trying to learn this. Thank you
Normally, I'd recommend using Files.copy just for it's simplicty, but since you need to "print" the content at the same time, we can make use of your code.
First, however, as a general rule of thumb, if you open it, you should close it. This makes sure that you're not leaving resources open which might affect other parts of your code.
See The try-with-resources Statement for more details.
Next, once you've read a line of text from the source file, you actually need to write it to the destination file, for example...
try (BufferedReader br = new BufferedReader(new FileReader("test.txt"))) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("Copied.txt"))) {
String text = null;
while ((text = br.readLine()) != null) {
System.out.println(text);
bw.write(text);
bw.newLine();
}
}
} catch (FileNotFoundException e) {
System.out.println("Error: " + e.getMessage());
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
You can use Files.copy() if you are using Java 1.7 or higher
File src = "your File";
File dest = "your copy target"
Files.copy(src.toPath(),dest.toPath());
Link to Javadoc
Change your FileWriter into a PrintStream:
PrintStream fw = new PrintStream(b);
Then you should be able to write to that file using:
fw.println(line);

Can't find the file path which created by myself in android source code

I am testing something.
I created assets folder in packages/apps/Camera/ and added the test.txt file in the folder.
But when I accessed the file in the onCreate() method according the following code fragment, I found I can't get the file.
File file = new File("/assets/test.txt");
BufferedReader reader = null;
try {
Log.v("jerikc","read the file");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
while ((tempString = reader.readLine()) != null) {
Log.v("jerikc","line " + line + ": " + tempString);
line++;
}
reader.close();
} catch (IOException e) {
Log.v("jerikc","exception");
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
The log were :
V/jerikc (3454): read the file
V/jerikc (3454): exception
I think I add the wrong path.("/assets/test.txt") .
So what's the right path?
Some other informations:
Where my real code is a Util Class, there isn't the context. If I add the context, the code structure will have a big change.
Thanks.
You have to read assets like below
AssetManager mAsset = context.getAssets();
InputStream is = mAsset.open("test.txt");
you can get the path from assest folder by this way...try this...
File file = new File("file:///assets/test.txt");
instead of this..
File file = new File("/assets/test.txt");

Categories