我一直试图弄清楚如何从.txt文件中读取。我知道如何阅读整个文件,但我在阅读文件中两个特定点之间遇到困难。 我也试图使用扫描仪类,这是我到目前为止:
public void readFiles(String fileString)throws FileNotFoundException{
file = new File(fileString);
Scanner scanner = null;
line="";
//access file
try {
scanner = new Scanner(file);
}
catch (FileNotFoundException e) {
System.out.println("File not found.");
}
// if more lines in file, go to next line
while (scanner.hasNext())
{
line = scanner.next();
if (scanner.equals("BGSTART")) //tag in the txt to locate position
{
line = scanner.nextLine();
System.out.println(line);
lb1.append(line); //attaches to a JTextArea.
window2.add(lb1);//adds to JPanel
}
}
.txt文件看起来像这样:
BGSTART //内容 BGEND
运行程序时,没有任何内容发布到面板上。
我试图在这两点之间进行阅读。我没有从txt文件中阅读的经验。 有什么建议? 谢谢。
答案 0 :(得分:2)
假设BGSTART
和BGEND
在不同的行上,根据@ SubOptimal的问题,你需要这样做:
boolean tokenFound = false;
while (scanner.hasNextLine())
{
line = scanner.nextLine();
//line, not scanner.
if (line.equals("BGSTART")) //tag in the txt to locate position
{
tokenFound = true;
}
else if (line.equals("BGEND"))
{
tokenFound = false;
}
if(tokenFound)
{
System.out.println(line);
lb1.append(line); //attaches to a JTextArea.
window2.add(lb1);//adds to JPanel
}
}
一些改进:
try {
Scanner scanner = new Scanner(new FileInputStream(file));
//Moved the rest of the code within the try block.
//As it was before, if there where any problems loading the file, you would have gotten an error message (File not found)
//as per your catch block but you would then have gotten an unhandled null pointer exception when you would have tried to
//execute this bit: scanner.hasNextLine()
boolean tokenFound = false;
while (scanner.hasNextLine()) {
String line = scanner.nextLine().trim();
//line, not scanner.
if (line.equals("BGSTART")) //tag in the txt to locate position
{
tokenFound = true;
} else if (line.equals("BGEND")) {
tokenFound = false;
}
if ((tokenFound) && (!line.equals("BGSTART"))) {
System.out.println(line);
//I am not sure what is happening here.
//lb1.append(line); //attaches to a JTextArea.
//window2.add(lb1);//adds to JPanel
}
}
} catch (Exception e) {
System.out.println("File not found.");
}
文件内容:
do not show line one
do not show line two
BGSTART
this is a line
this is another line
this is a third line
BGEND
do not show line three
do not show line four
答案 1 :(得分:1)
为什么不使用子字符串?一旦找到了您的BGSTART和BGEND,您就可以在下面代码行中的某处捕获字符串:
StringBuilder sb= new StringBuilder();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
sb.append(line);
}
String capturedString = sampleString.substring(sb.toString().indexOf("BGSTART"),
sb.toString().indexOf("BGEND"));
希望这会有所帮助
答案 2 :(得分:0)
几乎不错,但你在做:
if (scanner.equals("BGSTART")) //tag in the txt to locate position
您应该在line
变量中找不到scanner
的文件内容
所以试试这个:
if (line.equals("BGSTART")) //tag in the txt to locate position