如何在文件中按名称搜索?

如何在包含名称和年龄的对象的文件中按名称查找?


我想从文件中按名称搜索它。我完成了将对象写入文件并从文件中读取的操作。


Demo object1 = new Demo(100,"saran");

Demo object2 = new Demo(20 ,"nivas");


ArrayList<Demo> list=new ArrayList<>();

try {

    FileOutputStream file=new FileOutputStream("C:\\Users\\SARANNIVAS\\Documents\\file\\obj");

    ObjectOutputStream out=new ObjectOutputStream(file);

    list.add(object1);

    list.add(object2);

    out.writeObject(list);


    out.close();

    file.close();


    System.out.println("object has been serialized");


} catch(IOException ex)

{

     ex.printStackTrace();

    System.out.println("exception is caught");

}



try {

    FileInputStream file=new FileInputStream("C:\\Users\\SARANNIVAS\\Documents\\file\\obj");

    ObjectInputStream in=new ObjectInputStream(file);

    ArrayList<Demo> list1=new ArrayList<>();

    list1=(ArrayList<Demo>)in.readObject();


    for(Demo d:list1) {

        System.out.println(d.a);

        System.out.println(d.b);

    }


} catch(IOException ex) { 

    System.out.println("IOException is caught"); 

}


牧羊人nacy
浏览 110回答 1
1回答

皈依舞

我假设您正在尝试搜索您从文件中读回的数组列表。它是否正确?您可以使用类似...的方式搜索列表public class DemoDemo {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; Demo object1 = new Demo(100,"saran");&nbsp; &nbsp; &nbsp; &nbsp; Demo object2 = new Demo(20 ,"nivas");&nbsp; &nbsp; &nbsp; &nbsp; List<Demo> list=new ArrayList<>();&nbsp; &nbsp; &nbsp; &nbsp; list.add(object1);&nbsp; &nbsp; &nbsp; &nbsp; list.add(object2);&nbsp; &nbsp; &nbsp; &nbsp; list&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.filter(d1 -> d1.name.equalsIgnoreCase("saran"))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .forEach(d2 -> System.out.println(d2.name + " of age " + d2.age));&nbsp; &nbsp; }}class Demo {&nbsp; &nbsp; public final int age;&nbsp; &nbsp; public final String name;&nbsp; &nbsp; public Demo (int age, String name) {&nbsp; &nbsp; &nbsp; &nbsp; this.age = age;&nbsp; &nbsp; &nbsp; &nbsp; this.name = name;&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java