将数据存储到文件中一次,并在再次运行代码后避免任何更改

时间:2017-11-20 00:56:46

标签: java arrays java.util.scanner

我的代码

这里我从用户那里取一个名字并将其保存到文件中,我的目的是给该名称一个索引(Out)并将其保存到一个文件中,这样每次运行代码时,我仍然会有相同的名称和索引(不是新值)。那我怎么能这样做呢?

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class h_main {
  public static void main(String[] args) {
    contact[] table = new contact[3]; //Create an object of contact class
    int tablesize = 3;

    // Input from user

    //**Inserting from user**//
    Scanner reader = new Scanner(System.in); // Reading from System.in
    System.out.println("Enter a name: ");
    String names = reader.nextLine();       

    // Save the inserted name inside a table array with an index Out(from the hash function)

    int Out = calc_hash(names, tablesize);
    table[Out] = new contact();
    table[Out].Name = names;
    System.out.println(Out);

    // Writing

    for (int i = 0; i < table.length; i++) {
      FileWriter fWriter = null;
      BufferedWriter writer = null;
      try {
        fWriter = new FileWriter("text.txt");
        writer = new BufferedWriter(fWriter);
        writer.write(table[i].Name);
        writer.write(table[i].phone);
        writer.newLine();
        writer.close();
      }
      //   System.err.println("Your input of " + table[i].Name.length + " characters was saved.");
      catch (Exception e) {
        System.out.println("Error!");
      }

      // Reading

      // The name of the file to open.
      String fileName = "text.txt";

      // This will reference one line at a time
      String line = null;

      try {
        // FileReader reads text files in the default encoding.
        FileReader fileReader = new FileReader("text.txt");

        // Always wrap FileReader in BufferedReader.
        BufferedReader bufferedReader = new BufferedReader(fileReader);

        while ((line = bufferedReader.readLine()) != null) {
          System.out.println("Name: " + line);
        }

        // Always close files.
        bufferedReader.close();
      } catch (FileNotFoundException ex) {
        System.out.println(
          "Unable to open file '" +
          "text.txt" + "'");
      } catch (IOException ex) {
        System.out.println(
          "Error reading file '" +
          "text.txt" + "'");
        // Or we could just do this: 
        // ex.printStackTrace();
      }
    }
  }

  //**Generate hash function**//
  public static int calc_hash(String names, int table_size) {
    int i, l = names.length();
    int hash = 0;
    for (i = 0; i < l; i++) {

      hash += Character.getNumericValue(names.charAt(i));
      hash += (hash << 10);
      hash ^= (hash >> 6);
    }
    hash += (hash << 3);
    hash ^= (hash >> 11);
    hash += (hash << 15);
    if (hash > 0) return hash % table_size;
    else return -hash % table_size;
  }
}

Class contact
    public class contact {
    String Name ;
    int phone ; 
}

1 个答案:

答案 0 :(得分:0)

首次运行程序时文件不存在。执行此操作后,使用该文件的存在来确定该程序之前是否已运行。您的代码可能如下所示:

import java.nio.file.*;
import java.util.stream.*;

public class Main {

    public static void main(String[] args) {
        // It's recommended to follow Java naming and style conventions:
        // Class names always begin with an uppercase letter
        Contact[] table = new Contact[3];
        String fileName = "text.txt";

        Path file = Paths.get(fileName);
        // Check for persistence file:
        if(Files.exists(file)) {
            // If all you need to do is print each line, try this:
            try {
                Files.lines(file).forEach(l -> System.out.println("Name: " + l));
            } catch(IOException e) {
                System.err.println("Error reading data file!");             
            }
        } else {
            // Take data input
            Scanner scanner = new Scanner(System.in);
            // ...

            // When program is terminated, save everything:     
            try(BufferedWriter writer = Files.newBufferedWriter(file)) {
                // use writer to write data...
            } catch(IOException e) {
                System.err.println("Error writing data file!");
            }
        }

    }

}