Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在java中从文本文件中读取特定字段?_Java - Fatal编程技术网

如何在java中从文本文件中读取特定字段?

如何在java中从文本文件中读取特定字段?,java,Java,我有一个文本文件如下 Name :Kiran Id :1000 Address :Karol bagh Delhi Contact No. :9876612338 Band :L1 Salary :20000 Project :USM Type :Permanent Name :Tarun Id :1001 Address :Tarol begh

我有一个文本文件如下

Name        :Kiran   
Id      :1000  
Address     :Karol bagh Delhi  
Contact No. :9876612338  
Band        :L1  
Salary      :20000  
Project     :USM  
Type        :Permanent

Name        :Tarun  
Id      :1001  
Address     :Tarol begh Kolktta  
Contact No. :9876692338  
Band        :L2  
Salary      :30000  
Project     :GSM  
Type        :Permanent

Name        :Pavan  
Id      :1002  
Address     :Cottonpet Bangalore  
Contact No. :9889612338       
Band        :L3  
Salary      :40000  
Project     :PKM   
Type        :Contract
我想读取每个员工记录的Id和工资?如何使用文件I/O或任何其他方式进行读取?

public class EmployeeReader{
public class EmployeeReader {

    public static void main(String[] args) throws IOException {
        File file = new File("employees.txt");
        BufferedReader br = new BufferedReader(new FileReader(file));

        String line;
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        Map<String, String> map = new HashMap<String, String>();
        while ((line = br.readLine()) != null) {
            if (!line.trim().equals("")) {
                String[] tokens = line.split(":");
                if (tokens[0].trim().equals("Name") || tokens[0].trim().equals("Salary")) {
                    map.put(tokens[0].trim(),tokens[1].trim());                 
                }
            } else {
                list.add(map);
                map = new HashMap<String, String>();
            }
        }
        list.add(map);

        printList(list);
        br.close();
    }

    public static void printList(List<Map<String, String>> list) {
        for (Map<String, String> employee : list) {
            System.out.println("EMPLOYEE");
            for (Entry<String, String> entry : employee.entrySet()) {
                System.out.println("Key: " + entry.getKey());
                System.out.println("Value: " + entry.getValue());
            }
        }   
    }
}
公共静态void main(字符串[]args)引发IOException{ File File=新文件(“employees.txt”); BufferedReader br=新的BufferedReader(新文件读取器(文件)); 弦线; 列表=新的ArrayList(); Map Map=newhashmap(); 而((line=br.readLine())!=null){ 如果(!line.trim()等于(“”){ String[]tokens=line.split(“:”); if(tokens[0].trim().equals(“Name”)| | tokens[0].trim().equals(“Salary”)){ map.put(标记[0].trim(),标记[1].trim()); } }否则{ 列表。添加(地图); map=新的HashMap(); } } 列表。添加(地图); 打印列表(列表); br.close(); } 公共静态无效打印列表(列表){ 用于(映射员工:列表){ 系统输出打印项次(“员工”); for(条目:employee.entrySet()){ System.out.println(“Key:+entry.getKey()); System.out.println(“Value:+entry.getValue()); } } } }
这将对您有所帮助

public void readData() {
    String filePath = "/home/sharathgc/IdeaProjects/src/abc";
    File file = new File(filePath);
    String line = null;
    String pattern = "((Id :)(\\d)*)|(Salary :)(\\d)*";
    Pattern r = Pattern.compile(pattern);

    try {
        BufferedReader reader = new BufferedReader(new FileReader(file));
        while ((line = reader.readLine()) != null) {
            Matcher m = r.matcher(line);
            if (m.find()) {
                System.out.println(m.group());
            }
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
    } catch (IOException e) {
        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
    }
}

到目前为止你有什么收获。你试过什么?2.谷歌。3.将数据加载到内存中,即2D数组或(甚至更好)将其映射到对象。4.从填充的对象中“获取”所需内容。5.谷歌。6.谷歌it。这与javaee有关吗?我尝试了java文件I/O,它提供了所有数据。但我只想要每个员工的工资和Id。因为我想在UI上打印信息,所以我使用servlet。谢谢你的帮助。但它不起作用。程序不会被终止,也不会在控制台上打印任何内容。这只是一个额外的技巧,在循环外部创建Matcher,Matcher Matcher=Pattern.compile(“”)。Matcher(“”)。然后在循环内部,只需在
m.find()
之前重置匹配器,就像这样
matcher.reset(line)
。如果你需要匹配成千上万的东西,那么在每次迭代中不要创建和丢弃匹配器会更快。正则表达式有点不合适,我会使用:
(Id\\s*:)(\\d*)|(Salary\\s*:)(\\d*)
@brettw这是一个更好的正则表达式。谢谢你的即兴表演。嘿,它工作了。非常感谢。你知道比这更简单的解决方案吗?因为我是初学者,首先我想学习一些简单的东西。@ USER 741604你认为哪些部分是高级的?文件i/o(读取文件)是必需的。我猜地图/列表有点复杂,但它们会让生活变得更轻松。我已经做了必要的修改,现在你可以了。这应该行了。非常感谢。它行了。。
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class EmployeeData{
public static void main(String args[]){
   EmployeeData e=new EmployeeData();
   e.readData();
}
public void readData(){
String filePath = "Employees";
File file = new File(filePath);
String line = null;
String pattern = "(Id\\s*:)(\\d*)|(Salary\\s*:)(\\d*)";
Matcher matcher=Pattern.compile(pattern).matcher("");

try {
    BufferedReader reader = new BufferedReader(new FileReader(file));
    while ((line = reader.readLine()) != null) {
        matcher=matcher.reset(line);
        if (matcher.find()) {
            System.out.println(matcher.group());
        }
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();  //To change body of catch statement use File | Settings |    File Templates.
} catch (IOException e) {
    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
}
}
}