Reputation: 9
I'm creating a program, where i must read special text files. I have a problem with a reading text from specified word to another specified word(not including these words). Is using a scanner a good approach to this problem? I mean something like that:
"text1
text2
text3
text4
text5"
And i want to get from it String with "text2 text3 text4".
I tried using useDelimeter but I can not figure out how to apply it to this case. I created a method that allows me to skip lines, but this is not a good solution in the long run and it will work for only one specified file.
Here is one of my methods I want to make it here
private String readFile3(File file) {
try {
Scanner sc = new Scanner(file);
//skipLine(sc, 8);
sc.useDelimiter("R");
String sentence = sc.next();
textAreaD.setText(sentence);
} catch (FileNotFoundException e) {
System.out.println("No file");
}
return null;
}
Upvotes: 0
Views: 53
Reputation: 76
How about something like this:
private String readFile3(File file) {
try {
Scanner sc = new Scanner(file);
boolean save = false;
String sentence = "";
String temp = "";
while (sc.hasNextLine()) {
temp = sc.nextLine();
if (sentence.contains("text1")) {
if (!save) {
temp = sc.nextLine();
}
save = true;
}
if (sentence.contains("text5")) {
save = false;
}
if (save) {
sentence = sentence + temp;
}
}
// skipLine(sc, 8);
//sc.useDelimiter("R");
sentence = sentence.replaceAll("\\n", "");
textAreaD.setText(sentence);
} catch (FileNotFoundException e) {
System.out.println("No file");
}
return null;
}
Should read out all strings between "text1" and "text5". Maybe you have to do some more formatting and check if "text1" occurs more than one time, if you want to save that too, but i hope it helps you.
Upvotes: 0