我有一个文本文件列表,我需要读取一个特定的字符串,它始终以字符串“SWEUserName =”开头。我已经能够从日志中打印整行,但不仅仅是我需要的字符串。我想打印行号,而不是整行
到目前为止,这就是我所拥有的:
public static String [] openFile() throws FileNotFoundException, IOException{
String searchTech = "SWEUserName=";
int s;
String foundTech = "";
File logs = new File("C:\\Users\\wfedric\\Desktop\\GD\\Java\\Learning\\app\\src\\main\\java\\com\\fedrictechnologies\\learning\\FSDS2.txt");
Scanner scnr = new Scanner(logs);
int lineNumber = 1;
while(scnr.hasNextLine()){
String line = scnr.nextLine();
lineNumber++;
if(line.contains(searchTech)){
s = 10;
foundTech = lineNumber +" :"+ searchTech + s;
System.out.println(foundTech);
System.out.println(line);
}else;
}
return null;
}
我知道我错过了什么,但我不能为我的生活计算如何计算接下来的10个字符。我知道它代表我的代码,我只是打印行号,然后是我的searchTech变量和数字10.
我需要在searchTech之后保留10个字符。也许阵列是最好的方法?只是不确定:(
使用上面的代码,我有以下输出,我应该期待:
141 :SWEUserName=10
[09/04/14 EDT:8:15:48 AM- INFO- MASC1050141409832948329] - [ HomePageURL ] - ThinClient Home Page URL - https://wls.rio.directv.com/wpservsm_enu/start.swe?SWECmd=ExecuteLogin&SWENeedContext=false&SWEUserName=masc105014&SWEPassword=%5BNDSEnc-D%5Dji%2Fic25k%2FTB%2Fy7mqG2kcb2ndd1S3hgWC8Rfa4e1DvtwKWMGQmTzngA%3D%3D&
143 :SWEUserName=10
[09/04/14 EDT:8:15:48 AM- INFO- ] - [ webServiceRequest ] - Web service Call - RetryCounter: 0, URL: https://wls.rio.directv.com/wpservsm_enu/start.swe?SWECmd=ExecuteLogin&SWENeedContext=false&SWEUserName=masc105014&SWEPassword=%5BNDSEnc-D%5Dji%2Fic25k%2FTB%2Fy7mqG2kcb2ndd1S3hgWC8Rfa4e1DvtwKWMGQmTzngA%3D%3D&, Type: GET
第1行和第3行是我想要的通用格式,第2行和第4行是我遇到的问题,在searchTech之后返回特定值。
解决方案(在此过程中,我使用indexOf方法来包含日期,并将其保留在那里)
public class techMatching {
static int s;
static int d;
static String sTech;
static String dTech;
public static String [] openReadFile() throws FileNotFoundException, IOException{
String searchTech = "SWEUserName=";
String foundTech;
File logs = new File("C:\\FSDS2.txt");
Scanner scnr = new Scanner(logs);
int lineNumber = 1;
while(scnr.hasNextLine()){
String line = scnr.nextLine();
lineNumber++;
if(line.contains(searchTech)){
s = line.indexOf(searchTech);
sTech = line.substring(s+12,s+22);
d = line.indexOf("[");
dTech = line.substring(1, 22);
foundTech = lineNumber +": "+ "(" + dTech + ")" + "|"+ sTech.toUpperCase();
System.out.println(foundTech);
}else;
}
return null;
}
返回了预期的输出:
141: (09/04/14 EDT:8:15:48 )|MASC105014
143: (09/04/14 EDT:8:15:48 )|MASC105014
等等。 “”“”
答案 0 :(得分:2)
我建议您查看String类中可用的方法。使用indexOf(searchTech),您知道“SWEUserName =”在行中的位置。使用子字符串,您可以获得由行的一部分组成的字符串。