我需要帮助,只显示文本从一个文件中,让我们说的单词"Hello"开始,并在单词"Bye"结束。我能够扫描整个文本文件并打印它,但我需要它只打印出由两个变量定义的特定范围。这是我到目前为止,任何提示将不胜感激。谢谢!:)
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();
}
}
文件有多大?除非文件很大,否则将文件作为字符串读取,并去掉所需的位。
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")));
使用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();
}
}
我不确定你的意思是Hello和Bye必须在同一行上还是跨越多行?试试这个(修改startToken和endToken以适应):
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();
}
}
您可以使用状态变量来存储您是否处于"Hello"/"Bye"对之间。根据您在输入中找到的内容更改变量。根据您所处的状态打印文本
我把Java实现留给您。: -)