0

I'm trying to make a simple database where the person can choose either to add a new name or to list the current ones, and the program has to save these values in a text file. When they open the program again, it will load from the text file and already have some names listed. If the text file doesn't exist, it will create one. I know how to do most of things that I'll need, except how to read and write from a file (this is an expansion on a previous program, which only stored the names temporarily). I looked around on google but couldn't find anything that would work well/I can understand well. Could anyone help and explain how to, first, create and/or read from a file, and then write to it? Sorry if this seems like a dumb question, pretty new to Java :P

platelminto
  • 318
  • 3
  • 16
  • 1
    http://docs.oracle.com/javase/tutorial/essential/io/file.html – DHerls Feb 25 '15 at 22:33
  • possible duplicate of [Java: How to create a file and write to a file?](http://stackoverflow.com/questions/2885173/java-how-to-create-a-file-and-write-to-a-file) – Chuck Vose Feb 26 '15 at 03:26

1 Answers1

1

To start from somewhere this can be easy example for you to understand how it works. It creates a *.txt* file then give it to Scanner for reading file.It reads line by line until end of file and prints console.If you want to write to a file you can use PrintWriter

After you finish your work do not forget to close Scanner.

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

public class ReadTextFile
{
  public static void main (String [] args) throws IOException 
  {
    File inFile = new File ("input.txt");

    Scanner sc = new Scanner (inFile);
    while (sc.hasNextLine())
    {
      String line = sc.nextLine();
      System.out.println (line);
    }
    sc.close();
  }
}