我试图弄清楚如何在给定的文本文件中找到字符串的第一个实例,开始计算从第一行开始的行数与该字符串的实例,然后在找到另一个/不同的字符串时停止计数一条新线。
基本上我有一个文本文件,如:
CREATE PROCEDURE "dba".check_diff(a smallint,
b int,
c int,
d smallint,
e smallint,
f smallint,
g smallint,
h smallint,
i smallint)
RETURNING int;
DEFINE p_ret int;
LET p_ret = 0;
END IF;
RETURN p_ret;
END PROCEDURE;
我只想找到“CREATE PROCEDURE”的第一个实例并增加一个变量,直到我到达“END PROCEDURE;”的实例,然后重置变量。
我一直在尝试的是...
import java.io.*;
public class countFile
{
public static void main(String args[])
{
try
{
int i = 0;
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("C:/results.txt");
// Stream to write file
FileOutputStream fout = new FileOutputStream("C:/count_results.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null)
{
if (strLine.contains("CREATE PROCEDURE"))
{
while (!strLine.contains("END PROCEDURE;"))
{
i++;
break;
}
new PrintStream(fout).println (i);
}
}
//Close the input stream
in.close();
fout.close();
}
catch (Exception e)
{
//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
但是,这只是计算“CREATE PROCEDURE”实例的总数,并在每次递增时写出变量 i ......不是我要找的。
有什么帮助吗?
找到的解决方案:
import java.io.*;
public class countFile
{
public static void main(String args[])
{
try
{
int i = 0;
boolean isInProcedure = false;
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("C:/results.txt");
// Stream to write file
FileOutputStream fout = new FileOutputStream("C:/count_results.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
// Read File Line By Line
while ((strLine = br.readLine()) != null)
{
// If the line contains create procedure...
if (strLine.contains("CREATE PROCEDURE"))
{
// Set this flag to true
isInProcedure = true;
}
// If the line contains end procedure, stop counting...
if (strLine.contains("END PROCEDURE;"))
{
// Write to the new file
new PrintStream(fout).println(i);
// Set flag to false
isInProcedure = false;
// Reset counter
i = 0;
}
// Used to count lines between create procedure and end procedure
else
{
if (isInProcedure == true)
{
//Increment the counter for each line
i++;
}
}
}
//Close the input stream
in.close();
fout.close();
}
catch (Exception e)
{
//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}