I need help displaying only text from within a file that begins with lets say the word "Hello" and ends at the word "Bye". I'm able to scan the whole text file and print it, but I need it to only print out a specific range def开发者_Go百科ined by two variables. This is what I have so far, any tips will be appreciated. Thanks! :)
public static void main(String[] args) {
// TODO code application logic here
File fileName = new File("hello.txt");
try {
Scanner scan = new Scanner(fileName);
while (scan.hasNextLine()) {
String line = scan.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
How big is the file? I unless its large, read the file as a string and cut out the bit you want.
File file = new File("Hello.txt");
FileInputStream fis = new FileInputStream(file);
byte[] bytes = new byte[(int) file.length()];
fis.read(bytes);
fis.close();
String text = new String(bytes, "UTF-8");
System.out.println(text.substring(text.indexOf("START"), text.lastIndexOf("END")));
Using Apache FileUtils
String text = FileUtils.readFileToString("hello.txt");
System.out.println(text.substring(text.indexOf("START"), text.lastIndexOf("END")));
public static void main(String[] args) {
// TODO code application logic here
File fileName = new File("hello.txt");
try {
Scanner scan = new Scanner(fileName);
while (scan.hasNextLine()) {
String line = scan.nextLine();
System.out.println(line);
int indexHello = line.lastIndexOf("hello",0);
int indexBye = line.indexOf("bye". indexHello);
String newString = line.substring(indexHello, indexBye);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
I'm not sure whether you meant that Hello and Bye had to be on the same line or spanned over multiple lines? Try this (modify startToken and endToken to suit):
public static void main(String[] args) {
// TODO code application logic here
File fileName = new File("hello.txt");
try {
String startToken = "Hello";
String endToken = "Bye";
boolean output = false;
Scanner scan = new Scanner(fileName);
while (scan.hasNextLine()) {
String line = scan.nextLine();
if (!output && line.indexOf(startToken) > -1) {
output = true;
line = line.substring(line.indexOf(startToken)+startToken.length());
} else if (output && line.indexOf(endToken) > -1) {
output = false;
System.out.println(line.substring(0, line.indexOf(endToken)));
}
if (output) {
System.out.println(line);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
You can use a state variable to store whether you are between a "Hello" / "Bye" pair or not. Change the variable according to what you find in the input. Print text according to the state you are in.
I leave the implementation in Java to you. :-)
精彩评论