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.
Related
I have to modify a text file in java.
eg this is the file before modify
line
line
line
line
line
line
and after it should look like:
line
line
this is another
line
line
line
line
So don't write over anything, only add a line between the 2. and 3. line, and the original 3. line will be the new 4. line.
A way is to make a temp file, write every line in it, and where I want to modify I do the modification. Than delet the original, and rename the temp file. Or read the temp file and write it to te original file.
But is there any way to read and modify a file like I want using the same class in java?
thx!
You can read and modify to and from a file in Java at the same time. The problem you have though is that you need to insert data here, in order to do that everything after the new line needs to be shuffled down and then the length of the file extended.
Depending on exactly what and why you are trying to do there are a number of ways to do this, the easiest is probably to scan the file copying it to a new location and inserting the new values as you go. If you need to edit in place though then it's more complicated but essentially you do the same thing: Read X characters to a buffer, overwrite the X characters in the file with the new data, read next X characters. Overwrite the just-read characters from the first buffer. Repeat until EOF.
Think of files on disk as arrays - if you want to insert some items into the middle of an array, you need to shift all of them to make room.
The only safe way is to create a new temp file, copy the old file line by line and then rename it, just as you suggested. By updating the same file directly on the disk you risk losing the data if anything goes wrong and you would use a lot of memory.
Try this:
public void writeAfterNthLine(String filename, String text, int lineno) throws IOException{
File file = new File(filename);
File temp = File.createTempFile("temp-file-name", ".tmp");
BufferedReader br = new BufferedReader(new FileReader( file ));
PrintWriter pw = new PrintWriter(new FileWriter( temp ));
String line;
int lineCount = 0;
while ((line = br.readLine()) != null) {
pw.println(line);
if(lineCount==lineno){
pw.println(text);
}
lineCount++;
}
br.close();
pw.close();
file.delete();
temp.renameTo(file);
}
The code is not tested, but it should work, you can improve the code with several validations and exception handling
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 have to modify a text file in java.
eg this is the file before modify
line
line
line
line
line
line
and after it should look like:
line
line
this is another
line
line
line
line
So don't write over anything, only add a line between the 2. and 3. line, and the original 3. line will be the new 4. line.
A way is to make a temp file, write every line in it, and where I want to modify I do the modification. Than delet the original, and rename the temp file. Or read the temp file and write it to te original file.
But is there any way to read and modify a file like I want using the same class in java?
thx!
You can read and modify to and from a file in Java at the same time. The problem you have though is that you need to insert data here, in order to do that everything after the new line needs to be shuffled down and then the length of the file extended.
Depending on exactly what and why you are trying to do there are a number of ways to do this, the easiest is probably to scan the file copying it to a new location and inserting the new values as you go. If you need to edit in place though then it's more complicated but essentially you do the same thing: Read X characters to a buffer, overwrite the X characters in the file with the new data, read next X characters. Overwrite the just-read characters from the first buffer. Repeat until EOF.
Think of files on disk as arrays - if you want to insert some items into the middle of an array, you need to shift all of them to make room.
The only safe way is to create a new temp file, copy the old file line by line and then rename it, just as you suggested. By updating the same file directly on the disk you risk losing the data if anything goes wrong and you would use a lot of memory.
Try this:
public void writeAfterNthLine(String filename, String text, int lineno) throws IOException{
File file = new File(filename);
File temp = File.createTempFile("temp-file-name", ".tmp");
BufferedReader br = new BufferedReader(new FileReader( file ));
PrintWriter pw = new PrintWriter(new FileWriter( temp ));
String line;
int lineCount = 0;
while ((line = br.readLine()) != null) {
pw.println(line);
if(lineCount==lineno){
pw.println(text);
}
lineCount++;
}
br.close();
pw.close();
file.delete();
temp.renameTo(file);
}
The code is not tested, but it should work, you can improve the code with several validations and exception handling
I have a text file which I have a BufferedReader read from.
String sCurrentLine;
File myFile = new File("/sdcard/file.txt");
BufferedReader buf = new BufferedReader(new FileReader(myFile));
while ((sCurrentLine = buf.readLine()) != null) {
}
What I want to do is read a specific line and then replace it with something else whilst leaving the rest of the file alone. How should I do this?
Create a temporary file
Read through the file file.txt, write the output to the temporary file making the replacement as necessary
Close the file
Delete/backup the original file
Rename the temporary file to the original file
I have no idea how to do the following: I want to process a really huge textfile (almost 5 gigabytes). Since I cannot copy the file into temporarily memory, I thought of reading the first 500 lines (or as many as fit into the memory, I am not sure about that yet), do something with them, then go on to the next 500 until I am done with the whole file.
Could you post an example of the "loop" or command that you need for that? Because all the ways I tried resulted in starting from the beginning again but I want to go on after finishing the previous 500 lines.
Help appreciated.
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
ArrayList<String> allLines = new ArrayList<String>();
while((line = br.readLine()) != null) {
allLines.add(line);
if (allLines.size() > 500) {
processLines(allLines);
allLines.clear();
}
}
processLines(allLines);
Ok so you indicated in a comment above that you only want to keep certain lines, writing them to a new file based on certain logic. You can read in one line at a time, decide whether to keep it and if so write it to the new file. This approach will use very little memory since you are only holding one line at a time in memory. Here is one way to do that:
BufferedReader br = new BufferedReader(new FileReader(file));
String lineRead = null;
FileWriter fw = new FileWriter(new File("newfile.txt"), false);
while((lineRead = br.readLine()) != null)
{
if (true) // put your test conditions here
{
fw.write(lineRead);
fw.flush();
}
}
fw.close();
br.close();