Introduction
I challenged myself with this proyect.
I need to modify data at a specific line on a .txt without doing the next things:
- Loading everything on memory (Maps, Lists, Arrays...)
- Having to copy the file (such as -> this) and thus eating space on the computer (imagine a huge file, massive!)
- No relational DBs and stuff alike
A simple .txt file will have everything!
Text file
1;asd1324;2019-05-22 18:28:56;0;0;
2;asd1324;2019-05-22 18:28:56;0;0;
3;asd1324;2019-05-22 18:28:56;0;0;
4;asd1324;2019-05-22 18:28:56;0;0;
5;asd1324;2019-05-22 18:28:56;0;0;
6;asd1324;2019-05-22 18:28:56;0;0;
follows this format which are Strings with ";" as separator.
My code try which works for numbers from 0 to 9
(0 to 9 means this first number -> 1;asd1324;2019-05-22 18:28:56;0;0;)
public static void test(int lineNumber, String data)
{
String line;
try{
System.out.println("----DEBUG TEST----\n");
RandomAccessFile file = new RandomAccessFile("parking.txt", "rw");
System.out.println("File pointer is: " + file.getFilePointer());
System.out.println("Line size is: " + file.readLine().length());
System.out.println("Read line is: " + (line = file.readLine()) + " with size: " + line.length());
file.seek(line.length());
System.out.println("File pointer is: " + file.getFilePointer());
file.writeChars("\n");
file.writeBytes("7;asd1324;2019-05-22 18:28:56;0;0;");
file.writeChars("\n");
System.out.println("File pointer is: " + file.getFilePointer());
System.out.println("Line size is: " + file.readLine().length());
System.out.println("Read line is: " + (line = file.readLine()) + " with size: " + line.length());
file.seek(lineNumber);
file.close();
}catch(IOException e){System.out.println(e);}
System.out.println("\n----DEBUG TEST----\n");
}
Understanding the problem
The string -> 1;asd1324;2019-05-22 18:28:56;0;0;
- Those last two '0' will be another date format as "yy/MM/dd HH:mm:ss" and a random (int) which add more length and it going to mess with the .txt
Example: 1;asd1324;2019-05-22 18:28:56;2019-06-01 10:11:16;100;
- The first String is a number from 0 to the last entry number (it's a code)
I want to add them by replacing the String on it's position.
Notes
We will know at all times the size of the string we are going to modify (methods) and act accordingly.
What do I expect from this
Being able to modify the line from a file in Java. Which could be also a general method for this action.