JAVA扫描文本文件,只显示两个关键字/变量之间的文本

JAVA扫描文本文件,只显示两个关键字/变量之间的文本,java,Java,我需要帮助只显示一个文件中的文本,该文件以“Hello”开头,以“Bye”结尾。我可以扫描整个文本文件并打印它,但我需要它只打印出由两个变量定义的特定范围。这就是我目前所拥有的,任何提示都将不胜感激。谢谢!:) 档案有多大?除非文件很大,否则将其作为字符串读取,然后剪下所需的位 File file = new File("Hello.txt"); FileInputStream fis = new FileInputStream(file); byte[] bytes = new byte[(i

我需要帮助只显示一个文件中的文本,该文件以“Hello”开头,以“Bye”结尾。我可以扫描整个文本文件并打印它,但我需要它只打印出由两个变量定义的特定范围。这就是我目前所拥有的,任何提示都将不胜感激。谢谢!:)


档案有多大?除非文件很大,否则将其作为字符串读取,然后剪下所需的位

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")));
使用apachefileutils

String text = FileUtils.readFileToString("hello.txt");
System.out.println(text.substring(text.indexOf("START"), text.lastIndexOf("END")));

我不确定你是说Hello和Bye必须在同一行还是跨越多行?尝试此操作(修改startToken和endToken以适应):


您可以使用状态变量来存储您是否处于“Hello”/“Bye”对之间。根据您在输入中找到的内容更改变量。根据您所处的状态打印文本


我将Java实现留给您。:-)

您可以使用状态变量来存储您是否处于“Hello”/“Bye”对之间。根据您在输入中找到的内容更改变量。根据您所在的州打印行。使用fis工作,谢谢!现在我们来看看如何让它只显示一次,因为它们在整个文本文件中都有多个“Bye”,并且它包含了所有这些内容。但确实取得了进展,再次感谢!您想从第一个Bye(使用indexOf)开始,还是从最后一个Bye开始?你已经决定了。
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 {
        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();
    }
}
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();
    }
}