Replacing each line of a file
Hello,
i have this txt file with a layout like this
Code:
50 - 3
52 - 8
53 - 35
54 - 14
56 - 23
58 - 45
60 - 28
62 - 89
64 - 57
66 - 466
68 - 167
70 - 1271
72 - 782
i want to keep only the first number (before the " - ") on each line of the file.
How can i do this using bufferedreader and bufferedwriter? I was thinking about getting the indexOf the " - " and then using the substring method to remove the rest of the line but i mess up somehow...
Thanks for your time :)
Re: Replacing each line of a file
Hello.
Your idea is tottaly okey.
Here is simple example:
Code:
public static void main(String [] args)
{
// read every line
String input = "50 - 3";
//find position of " -" {space}-
int position = input.indexOf(" -");
//use substring
String firstNumber = input.substring(0, position);
System.out.println(firstNumber);
}
Just read line and get your numbers :) ( HINT: google: java file read every line )
I hope it will help u.
Have fun :)
Re: Replacing each line of a file
this is my code currently:
Code:
public static void originalDumpReplacer() throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("dump2.txt"));
int lines = 0;
while (reader.readLine() != null) {
lines++;
}
System.out.println("Item count to be dumped: " + lines);
System.out.println("Now replacing the original Dump...");
BufferedWriter writer = new BufferedWriter(
new FileWriter("dump2new.txt", true));
for (int i = 0; i < lines; i++) {
String nextLine = reader.readLine();
int position = nextLine.indexOf(" - ");
String firstNumber = nextLine.substring(0, position);
writer.write(firstNumber);
writer.newLine();
writer.flush();
}
writer.close();
reader.close();
}
I end up with a NullPointerException at int position = nextLine.indexOf(" - ");
and an empty txt file (dump2new.txt)
:=-:
Re: Replacing each line of a file
Hello.
Fast look on your code:
in while loop your reader reached till EOF.
from link: bla bla returns null if the end of the stream has been reached
Think about it :)
Best solution, place breakpoint line before int position = nextline.... and debug it :)
Re: Replacing each line of a file
Oh thanks, i understand more about how bufferedreader and bufferedwriter work now!
Added a second reader and everything went like a charm.
Thanks alot for your time :(nod):
Re: Replacing each line of a file
You only actually need the one reader, and a single loop.
Simply read a line, process it (ie get the part of the string you want) and write that out.
Code:
String line;
while ((line = reader.readLine()) != null) {
write substring line.
}