gpt4 book ai didi

java - 如何读取字符串变量后的接下来 10 个字符

转载 作者:行者123 更新时间:2023-12-02 05:29:49 25 4
gpt4 key购买 nike

我有一个文本文件列表,需要从中读取特定字符串,该字符串前面始终带有字符串“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。

我需要 s 保留 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

第一行和第三行是我想要的通用格式,第二行和第四行是我在 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

等等。“”“”

最佳答案

我建议您查看 String 类中可用的方法。使用indexOf(searchTech),您可以知道“SWEUserName=”在行中的位置。使用子字符串,您可以获得由该行的一部分组成的字符串。

关于java - 如何读取字符串变量后的接下来 10 个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25672656/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com