从java文件中读取单词赋值
在java中从文件中读取单词及其赋值从java文件中读取单词赋值,java,Java,在java中从文件中读取单词及其赋值 public static void main(String [] args) throws IOException { readLines("F:\\myfile.txt"); } public static List<String> readLines(String filename) throws IOException { String word = "nameId"; FileReader fileRe
public static void main(String [] args) throws IOException {
readLines("F:\\myfile.txt");
}
public static List<String> readLines(String filename) throws IOException
{
String word = "nameId";
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null)
{
lines.add(line);
// if(line.contains(name)){
// System.out.println(line);
word="nameId";
if(line.indexOf(word) != -1)
{
System.out.println("Return Value : " + String.valueOf(line) );
}
// }
// System.out.println(line);
}
bufferedReader.close();
return lines;
}
publicstaticvoidmain(字符串[]args)引发IOException{
读取行(“F:\\myfile.txt”);
}
公共静态列表读取行(字符串文件名)引发IOException
{
字符串word=“nameId”;
FileReader FileReader=新的FileReader(文件名);
BufferedReader BufferedReader=新的BufferedReader(文件阅读器);
列表行=新的ArrayList();
字符串行=null;
而((line=bufferedReader.readLine())!=null)
{
行。添加(行);
//if(行包含(名称)){
//系统输出打印项次(行);
word=“nameId”;
if(行索引of(字)!=-1)
{
System.out.println(“返回值:“+String.valueOf(line));
}
// }
//系统输出打印项次(行);
}
bufferedReader.close();
回流线;
}
myfile.txt包含以下行:-
完整的标记前面和后面是输入nameId=4456566262445454,它与分隔符模式匹配。此方法在等待扫描输入时可能会阻塞,即使之前调用Scanner.hasNext返回true也是如此
低于所需的输出
所需输出:
4456566262445454
请帮忙 试试看
if(line.indexOf(word) != -1) {
String nameId = line.replaceAll("(.*)(nameId=(\\w+))(.*)", "$3");
System.out.println("Return Value : " + nameId);
}
您可以将数字与正则表达式匹配
String regular = "nameId=([0-9]*)";
Matcher m = Pattern.compile(regular).matcher(line);
while (m.find()) {
System.out.println(m.group(1));
}
您可以按如下方式进行操作:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
// A sample text (it will be read from the text file by your code)
String text = "A complete token is preceded and followed by input nameId=4456566262445454 that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of Scanner.hasNext returned true";
Matcher m = Pattern.compile("nameId=([\\w+]*)").matcher(text);
while (m.find()) {
System.out.println(m.group(1));
}
}
}
输出:
4456566262445454
您的问题是什么?需要从myfile.txt文件中读取nameId赋值,即4456566262445454