I'm trying to read a system file on the Nexus 5 and rewrite it to a second file with some modifications I will make. The problem is even without my modifications the file is not written completely. Il gets almost to the end and then stops writing always at the same place. Stops at line 450 and only writes <path name when it should write <path name="voice-tty-full-headphones"> and continue for 30 more lines...
Strangely if I export to a textview everything is there so the problem is not when reading the file but when writing to the new one. I have attached a copy of the file i'm working with along with a copy of the file thats being generated. I really have no idea what to try from here.
//Output File
File outputFile = new File(Environment.getExternalStorageDirectory().getPath(), "/xxx/mixer_paths.xml");
outputFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(outputFile);
OutputStreamWriter myOutWriter =new OutputStreamWriter(fOut);
//Input File
File internalStorage = Environment.getRootDirectory();
File inputFile = new File(internalStorage,"/etc/mixer_paths.xml");
BufferedReader br = new BufferedReader(new FileReader(inputFile));
StringBuilder text = new StringBuilder();
String line;
while ((line = br.readLine()) != null )
{
text.append(line+"\n");
}
myOutWriter.append(text);
textView.setText(text);
https://www.dropbox.com/s/7p1cgu7ziyzydh1/mixer_paths_original.xml
https://www.dropbox.com/s/zs03xt4k52vetek/mixer_paths_new.xml
Thanks
Did you forget to close the writer? I've made this mistake myself. Always close your readers and writers when you are done with them. It frees up the resources and in the case of the writer, makes sure to finish writing!
Related
There are so many Input/Output Classes in Java.
It is really a mess. You do not know which to use.
Which functions does operating system offer ? There will be one
to read one byte of a file or many bytes of a file I guess.
So for example if I use this.
String path = "C:\\Users\\myName\\test.txt";
FileOutputStream fos = new FileOutputStream(path);
fos.write(333);
If I open it with a text editor it shows me letter "G" . Already I do not understand this.
And this code does not write anything, the file is empty weirdly.
String path = "C:\\Users\\myName\\test.txt";
FileOutputStream fos = new FileOutputStream(path);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos));
out.write("something");
All these I/O classes just confuse me. What does buffered mean. It reads 1000 Bytes at once. So
there is operating function to straight away read 1000 Bytes of a file I guess.
You need to close the instances of BufferedWriter out and FileOutputStream fos, after invoking the out.write("something"), then only the file gets created successfully with the contents you are trying to write.
public static void main(String[] args) throws IOException {
String path = "C:\\Users\\myName\\test.txt";
FileOutputStream fos = new FileOutputStream(path);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos));
out.write("something");
out.close(); // Closes the stream, flushing it first.
fos.close(); // Closes this file output stream and releases any system resources associated with this stream.
}
Closing the instances of BufferedWriter and FileOutputStream will solve the issue.
fos.write(333) => The number has been written to the file and when you open the file it opens in ASCII format. You can use below code.
public static void main(String[] args) throws IOException {
FileWriter fw=new FileWriter("D:\\test.txt");
fw.write("Hello! This is a sample text");
System.out.println("Writing successful");
fw.close();
/* your code
String path = "D:\\test1.txt";
FileOutputStream fos = new FileOutputStream(path);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos));
out.write("Hello! This is a sample text");
out.close();
fos.close();
*/
}
There are so many Input/Output Classes in Java. It is really a mess. You do not know which to use.
The Files class is by far the easiest to use. For instance,
Files.writeString(Paths.get("test.txt"), "hello world!");
creates a text file named "test.txt" containing the text "hello world!".
The other classes are only needed if you want to do something fancy (for instance, deal with files too big to fit in main memory). For instance, suppose you wanted to read a huge log file (hundreds of gigabytes long) and wanted to write each line containing a particular word to another file. If you were to open the file with
Files.readAllLines(Paths.get("huge.log"));
you'd receive an OutOfMemoryError because the file doesn't fit in main memory. To work around that, we must read the file piece-wise, and that is what all those Reader and Writer classes (or InputStream and OutputStream, if you're dealing with binary files) are good for:
try (
var reader = Files.newBufferedReader(Paths.get("huge.log"));
var writer = Files.newBufferedWriter(Paths.get("interesting.log"));
) {
String line;
while ((line = reader.readLine()) != null) {
if (line.contains(searchWord)) {
writer.write(line);
writer.write('\n');
}
}
}
As you can see, their use is quite a bit more complicated. For one, we must close the Reader and Writer once we are done with them, which is easiest accomplished with the try with resources statement shown above.
Closing is necessary because most operating systems limit the number of files that can be open at once. Closing also gives any Buffered* classes the opportunity to empty their buffers, ensuring that any data still in buffers is passed on to the file system.
If we fail to close, as you did in your example code, the file remains open until our program exits, upon which time any data in the buffers is lost, resulting in the incomplete file you found.
Basically, I'm trying to create a simple database app with automatically generated IDs in each student entry. The program reads the previous highest ID and adds 1 to it to create the next one.
However, even though the text document has numbers in it, BufferedReader keeps returning null when using readLine
I checked if my int parsing was the issue, but i realized it was the bufferedreader by saving the readline to a variable then printing it, where I got the result of null. I also tried using scanner file reading which didn't work, and I checked all related classes and methods to try to figure it out.
This code creates the topsid file and writes 0 to initialize it, which is being read as null
if(MiscProcesses.firstStartup() == false) //method that checks if these files exist
{
File topsid = new File("topsid.txt");
FileWriter fw = new FileWriter(topsid);
fw.write("0");
fw.close();
}
This code is responsible for reading the file and hence finding a higher id value
Student (String[] studata)
{
//checking highest SID
File topsid = new File("topsid.txt");
FileWriter fw = new FileWriter(topsid);
FileReader fr = new FileReader(topsid);
BufferedReader br = new BufferedReader(fr);
//checking high sid file and getting new sid
String test = br.readLine();
System.out.println(test+" <test"); <this ends up printing null
int sid;
sid = Integer.parseInt(test)+1;
System.out.println(sid);
fw.write(Integer.toString(sid));
this.id = sid;
...
br.close();
fr.close();
fw.close();
}
When I open the topsid file before the second code runs, it's all fine and the file contains a zero.
I would expect the bufferedreader to read "0" but it just reads null, and when I open the file after the code runs, the data inside gets erased.
FileWriter fw = new FileWriter(topsid);
FileReader fr = new FileReader(topsid);
BufferedReader br = new BufferedReader(fr);
Creating the FileWriter like this will stomp the existing file before you read its contents.
If you want to read something from the file, then write something back after, create the FileWriter after you have read from it.
I want to edit certain values(a row values) of a csv file based on a specific value of that row (an id). I am able to read and write (append) the values in it but cannot figure out how to edit and delete them.
Here is a small fragment of code for what I am doing for reading the file and appending values:
FileWriter writer = new FileWriter("file.csv", true);
try {
FileInputStream fstream = new FileInputStream("file.csv");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = br.readLine()) != null) {
String[] fields = strLine.split(",");
if (fields[1].equals("value") {
fields[1] = "different value";
}
writer.append(fields);
}
catch(...)
}
But I can't work out how to write the values back into the same spot in the file.
Unfortunately you can't open a single file for both reading and writing at the same time. You need to read the file and close it before opening it for writing.
The potential solutions are:
Write the output to a different file and then replace the original when complete
Keep all the output in internal variables then, once you've finished reading, close the file and reopen it for writing.
Assuming I have a txt file located in /mypath/sampletext.txt. How do I append a new line to the beginning of the file with the following in Java while preserving the original text file's contents?:
String startStr ="--Start of File--";
Looking for a way to do this without having to create an intermediary 2nd file and make modifications only to the existing file if possible.
Read file contents first, prepend new line to that like contents = newLine + contents, then write the new conent in the same file (dont append).
well,three ways ,may help you
1.
//true: is append text to fie
FileWriter write = new FileWriter("file_path",true);
writer.write(content);
//open randomFile and "rw"
randomFile = new RandomAccessFile("file_path", "rw");
// file length
long fileLength = randomFile.length();
//point to end index
randomFile.seek(fileLength);
//write
randomFile.writeBytes(content);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
out.write(conent);
New answer is updated...
In this I've use few more FileIO classes & may be their one is deprecated API but If you are aware with Java FileIO classes you can easily fix it.
Here I append new line at the start of file rather than append it to the end of file..
If any issue please comment again....
Try this, I think it will help you..
try
{
//Append new line in existing file.
FileInputStream fr = new FileInputStream("onlineSoultion.txt");
DataInputStream dr = new DataInputStream(fr);
String startStr = "--Start of File--\n";
//String startStr;
while (dr.available() > 0) {
startStr += dr.readLine();
//System.out.println(startStr);
}
dr.close();
fr.close();
FileOutputStream writer = new FileOutputStream("onlineSoultion.txt");
writer.write((new String()).getBytes());
writer.close();
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("onlineSoultion.txt", true)));
out.println(startStr);
out.close();
}
Here's the code I used, I get no errors or warnings but the file is empty, I created the aq.txt file and placed it in the workspace and it also shows in the project. I'm sure it's something stupid I'm missing but I just can't figure it out. Also, I tried all the other questions but the suggested answer is closing the stream and/or flushing it, both of which I do but they don't seem to work. Any help would be greatly appreciated!
Writer writer = null;
FileOutputStream fos= null;
try{
String xyz= "You should stop using xyz";
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(getFilesDir()+File.separator+"aq.txt")));
writer.write(xyz);
writer.flush();
}
catch(IOException e) {
System.out.println("Couldn't write to the file: " + e.toString());
}
finally{
if(writer != null){
try {
writer.close();
}
catch(IOException e1) {
e1.printStackTrace();
}
}
}
Try like this:
fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
writer = new BufferedWriter(new OutputStreamWriter(fos));
writer.write(xyz);
writer.flush();
Context class provides a helper method Context.openFileOutput(String name, int mode) that will return a FileOutputStream to you for a file located in your applications Files directory.
I don't see any immediate reason why your way would not work, but I know I've used this other way successfully.
EDIT: After re-reading your question I think you are confused about where this file is going to be written to. It will not get written to the project folder inside of your workspace. This is going to be written to the internal storage of the android device that you run it on. Every application gets its own chunk of storage space located at \data\data\[package-name]\Files\ Your file is going to get written to there so you won't be able to immediately open it up and see the contents of it (unless your device is rooted.) You will instead have to open it up with java code and print its contents to the Log or some other output method in order to verify that your write did/did not work.
EDIT 2: Reading the file
FileInputStream in = openFileInput(FILE_NAME);
InputStreamReader inputStreamReader = new InputStreamReader(in);
BufferedReader br = new BufferedReader(inputStreamReader);
String line = br.readLine();
Log.d("TAG", line);
This will read and output to the log the first line of the file.
This will certainly work :
File file = new File("fileName");
FileWriter fileWriter = new FileWriter(file);
BufferedWriter writer = new BufferedWriter(fileWriter);
writer.write("data to write in the file.");
writer.flush();