如何从文件中检索数据

时间:2017-05-21 16:08:14

标签: java file io

我应该如何检索text1的文件以用作登录信息.. 因为我已经在注册部分输入了详细信息..我想使用名字和员工ID作为登录部分的用户名和密码.. p / s:我在编码方面很弱..请原谅我凌乱的编码:) 这是我的代码。

import java.util.Scanner;
import java.io.*;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.FileReader;


public class TestMyException12 {

static void clear() {
    try {
        if (System.getProperty("os.name").contains("Windows"))
            new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
        else
            Runtime.getRuntime().exec("clear");
    } catch (IOException | InterruptedException ex) {}
}


public static void main(String[] args) {


System.out.println("1.Please register for new staff\n2.Staff login\n");
Scanner input1 = new Scanner(System.in);

FileWriter fWriter = null;
BufferedWriter writer = null;
int choice = input1.nextInt();




if (choice == 1) {
    System.out.println("======================Staff Registration==================\n");
    System.out.println("Please enter your personal details below:\n");

    System.out.println("Enter your first name:\n");
    Scanner scan = new Scanner(System.in);
    String text = scan.nextLine();

    System.out.println("Enter your last name:\n");
    Scanner scan1 = new Scanner(System.in);
    String text1 = scan.nextLine();

    System.out.println("Enter your NRIC:\n");
    Scanner scan2 = new Scanner(System.in);
    String text2 = scan.nextLine();

    System.out.println("Enter your Staff ID:\n");
    Scanner scan3 = new Scanner(System.in);
    String text3 = scan.nextLine();

    System.out.println("Enter your position:\n");
    Scanner scan4 = new Scanner(System.in);
    String text4 = scan.nextLine();

    try {
        fWriter = new FileWriter("text1.txt");
        writer = new BufferedWriter(fWriter);
        writer.write(text);
        writer.write(text1);
        writer.write(text2);
        writer.write(text3);
        writer.write(text4);
        writer.newLine();
        writer.close();
        System.err.println("Your input data " + text.length() + " was saved.");
    } catch (Exception e) {
        System.out.println("Error!");
    }
}
else {
    System.out.println("======================Staff Login===========================");

    System.out.println("\nLogin(Use your first name as username and id as password)");

    System.out.println("Enter Username : ");
    Scanner scan = new Scanner(System.in);
    String text = scan.nextLine();

    System.out.println("Enter Password : ");
    Scanner scan3 = new Scanner(System.in);
    String text3 = scan.nextLine();

    if (scan.equals(text) && scan.equals(text3)) {
        clear();
        System.out.println("Access Granted! Welcome!");
    } else if (scan.equals(text)) {
        System.out.println("Invalid Password!");
    } else if (scan.equals(text3)) {
        System.out.println("Invalid Username!");
    } else {
        System.out.println("Please register first!\n");
    }
}
}
}

3 个答案:

答案 0 :(得分:1)

这很简单,就像这样:

package com.coder.singleton;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class TestMyException12 {
    static void clear() {
    try {
        if (System.getProperty("os.name").contains("Windows"))
            new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
        else
            Runtime.getRuntime().exec("clear");
    } catch (IOException | InterruptedException ex) {
    }
}

public static void main(String[] args) {

    System.out.println("1.Please register for new staff\n2.Staff login\n");
    Scanner input1 = new Scanner(System.in);

    FileWriter fWriter = null;
    BufferedWriter writer = null;
    int choice = input1.nextInt();
    StringBuilder sb = new StringBuilder();
    String text = "";

    if (choice == 1) {
        System.out.println("======================Staff Registration==================\n");
        System.out.println("Please enter your personal details below:\n");

        System.out.println("Enter your first name:\n");
        text = input1.next();
        sb.append(text + "  ");

        System.out.println("Enter your last name:\n");
        text = input1.next();
        sb.append(text+ "   ");

        System.out.println("Enter your NRIC:\n");
        text = input1.next();
        sb.append(text+ "   ");

        System.out.println("Enter your Staff ID:\n");
        text = input1.next();
        sb.append(text+ "   ");

        System.out.println("Enter your position:\n");
        text = input1.next();
        sb.append(text+ "   ");
        input1.close();
        try {
            fWriter = new FileWriter("text1.txt");
            writer = new BufferedWriter(fWriter);
            writer.write(sb.toString());
            writer.newLine();
            writer.close();
            System.err.println("Your input data " + sb.length() + " was saved.");
        } catch (Exception e) {
            System.out.println("Error!");
        }

    }

    else {

        String savedName = "";
        String savedPassword = "";

        try {
            FileInputStream fis = new FileInputStream(new File("text1.txt"));
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis, "UTF-8"));

            String word = "";
            String [] arr = null;
            while ((word = bufferedReader.readLine())!= null) {

                arr = word.split("\\s+");

            }
            savedName = arr[0];
            savedPassword = arr[2];
            bufferedReader.close();


        } catch (Exception e) {
            // TODO: handle exception
        }

        System.out.println("======================Staff Login===========================");

        System.out.println("\nLogin(Use your first name as username and id as password)");

        System.out.println("Enter Username : ");
        String userName = input1.next();

        System.out.println("Enter Password : ");
        String password = input1.next();




        if (userName.equals(savedName) && password.equals(savedPassword)) {
            clear();
            System.out.println("Access Granted! Welcome!");
        }else if (userName.equals(savedName) && !password.equals(savedPassword)) {
            System.out.println("Invalid Password!");
        } else if (!userName.equals(savedName) && password.equals(savedPassword)) {
            System.out.println("Invalid Username!");
        } else {
            System.out.println("Please register first!\n");
        }

    }
}
}

答案 1 :(得分:0)

第一个,你应该在将寄存器信息保存到文件text1时插入分隔符(如newLine),如果没有,则无法区分信息字段。例如:

fWriter = new FileWriter("d:\\tmp\\pass.txt");
                writer = new BufferedWriter(fWriter);
                writer.write(text);
                writer.newLine();  //separator string
                writer.write(text1);
                writer.newLine();
                writer.write(text2);
                writer.newLine();
                writer.write(text3);
                writer.newLine();
                writer.write(text4);
                writer.newLine();
                writer.close();

然后,您应该检索注册信息(只是名字和工作人员)表单文件text1.txt

BufferedReader reader=new BufferedReader(new FileReader("text1.txt"));
            String firstName = reader.readLine();
            reader.readLine();
            reader.readLine();
            String passWord=reader.readLine();

final,将输入信息与读取信息进行比较。

if (firstName.equals(text) && passWord.equals(text3)) {
                System.out.println("Access Granted! Welcome!");
            }

答案 2 :(得分:0)

注册时 你必须在注册时插入一些分隔符(',','。',':','_',' - '等......)。

现在听说我正在使用“#”分隔符。

插入该数据和分隔符后。

现在在阅读时您必须使用该分隔符进行拆分,您可以访问该数据。在数组中

参见Bellow code ...

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


public class TestMyException12
{

        static void clear(){
            try {
               if (System.getProperty("os.name").contains("Windows"))
                   new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
               else
                   Runtime.getRuntime().exec("clear");
            } catch (IOException | InterruptedException ex) {}
         }


public static void main(String[] args) {


    System.out.println("1.Please register for new staff\n2.Staff login\n");
    Scanner input1 = new Scanner(System.in);

    FileWriter fWriter = null;
    BufferedWriter writer = null;
    int choice = input1.nextInt();




    if (choice == 1) {
        System.out.println("======================Staff Registration==================\n");
        System.out.println("Please enter your personal details below:\n");

        System.out.println("Enter your first name:\n");
        Scanner scan = new Scanner(System.in);
        String text = scan.nextLine();

        System.out.println("Enter your last name:\n");
        Scanner scan1 = new Scanner(System.in);
        String text1 = scan.nextLine();

        System.out.println("Enter your NRIC:\n");
        Scanner scan2 = new Scanner(System.in);
        String text2 = scan.nextLine();

        System.out.println("Enter your Staff ID:\n");
        Scanner scan3 = new Scanner(System.in);
        String text3 = scan.nextLine();

        System.out.println("Enter your position:\n");
        Scanner scan4 = new Scanner(System.in);
        String text4 = scan.nextLine();

          try {
                               fWriter = new FileWriter("text1.txt");
                               writer = new BufferedWriter(fWriter);
                               writer.write(text);
                               writer.write("#");
                               writer.write(text1);
                               writer.write("#");
                               writer.write(text2);
                               writer.write("#");
                               writer.write(text3);
                               writer.write("#");
                               writer.write(text4);

                               writer.close();
                               System.err.println("Your input data " + text.length() + " was saved.");
                             } catch (Exception e) {
                                 System.out.println("Error!");
        }


    }


   else
    {

        System.out.println("======================Staff Login===========================");

        System.out.println("\nLogin(Use your first name as username and id as password)");

        System.out.println("Enter Username : ");
        Scanner scan = new Scanner(System.in);
        String text = scan.nextLine();

        System.out.println("Enter Password : ");
        Scanner scan3 = new Scanner(System.in);
        String text3 = scan.nextLine();

        String datafile = "";

        try
        {
            FileReader fr = new FileReader("text1.txt");
            int i;

            while((i = fr.read()) != -1)
            {
                datafile = datafile+(char)i; // store all data into String obj from File
            }
        }
        catch(Exception e)
        {
            System.out.println("Error In Login : "+e);
        }


        String[] userval = datafile.split("#"); // split that data and create part of that data 

        for(int i = 0 ; i < userval.length ; i++)
        {
            System.out.println(i+">>>>>"+userval[i]);
        }
        // userval[] is array that is store all data from that file into part

        // after you can put any condition

        //System.out.println(text+">>>>>"+userval[0]);
        //System.out.println(text3+">>>>>"+userval[3]);

        if(text.equals(userval[0]) && text3.equals(userval[3]))
        {
            clear();
            System.out.println("Access Granted! Welcome!");
        }
        else
        {
            System.out.println("Please register first!\n");
        }
    }
}
}