Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/392.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_Input - Fatal编程技术网

Java 困在如何读取文件上

Java 困在如何读取文件上,java,input,Java,Input,帮我一下,我卡住了。。我们将制作两个程序,第一个是我们要求用户输入多少名员工、第一个姓名、姓氏、id……然后将其存储到名为names.db的文件中。。。我能够做到这一点…我被困在第二个程序上…该程序假设可以做到这一点…通过要求用户输入员工的第一个姓名来检索员工数据库,如果找到了员工,则打印该信息…如果没有,则打印未找到 import java.util.Scanner; import java.io.*; public class RetrieveInfo { public stati

帮我一下,我卡住了。。我们将制作两个程序,第一个是我们要求用户输入多少名员工、第一个姓名、姓氏、id……然后将其存储到名为names.db的文件中。。。我能够做到这一点…我被困在第二个程序上…该程序假设可以做到这一点…通过要求用户输入员工的第一个姓名来检索员工数据库,如果找到了员工,则打印该信息…如果没有,则打印未找到

import java.util.Scanner;
import java.io.*;

public class RetrieveInfo
{
    public static void main(String[] args) throws IOException
    {

    //create scanner object for keyboard input
    Scanner keyboard = new Scanner(System.in);

    //open file
    File file = new File("Employee.db");
    Scanner inputFile = new Scanner(file);

    //ask for employee name
    System.out.print("enter the name of the employee. ");
    String firstName =keyboard.nextLine();

    //here is where im stuck...read the file and check of the empoyee is     
    here. We are learning about loops some im pretty sure its going to be a loop


    }

}

您可能需要通过您的行,如果数据在当前行中,则打印它。读取文件后:

String expectedemployee = null
for(String line : Files.readAllLines(Paths.get("/path/to/file.txt")) {

    if(line.contains(firstName) {
         expectedemployee = line;
         break;
    }
}
if(expectedemployee != null) {
    // print
} else {
    // you don't have any employee corresponding
}
或者您可以使用BufferedReader

try (BufferedReader br = new BufferedReader(new FileReader(file))) {
    String line;
    while ((line = br.readLine()) != null || expectedemployee != null) {
       if(line.contains(firstName) {
          expectedemployee = line;
          break;
       }
    }
}

对于这种类型,使用数据库而不是文件会更好。如果您想要文件,那么您应该尝试使用对象输入/输出流。

您是否有一些已经尝试过的代码?如果我们不知道数据如何存储在您的文件中,我们可能无法帮助您。数据存储方式如下:John,Smith,ID,数据存储在您的文件中,每行一名员工?@Rhayene yea每行一名员工