Home Ask Login Register

Developers Planet

Your answer is one click away!

Haseeb Tahir February 2016

reading/writing variables from text files to variables

I need to make a system for storing customer information and all quotations to an external file as well as entering more customers, listing customers, and the same with the quotations. As well as this I need to link all quotations/customers to an ID. I basically need to do SQL in java. However, I really need help with my input and output system, and writing all info to an array. I have got two main pieces of code but they are very inefficient and I need some suggestions, improvements or an entirely different system. Input from file Code:

import java.io.*; //import classes
import java.util.ArrayList; 
import java.util.Iterator;
public class MyTextReader{
   public static void main(String[] args){
    String myDirectory = System.getProperty("user.dir");
    String fullDirectory = myDirectory + "\\myText.txt";
    String input_line = null;
       ArrayList<String> textItems = new ArrayList<String>(); //create array         list
        BufferedReader re = new BufferedReader(new FileReader(fullDirectory));
        while((input_line = re.readLine()) != null){
            textItems.add(input_line); //add item to array list
    }catch(Exception ex){
           System.out.println("Error: " + ex);
       Iterator myIteration = textItems.iterator(); //use Iterator to cycle list
       while(myIteration.hasNext()){ //while items exist
         System.out.println(myIteration.next()); //print item to command-line

Output to File

import java.io.FileWriter; //import classes
import java.io.PrintWriter;
public class MyTextWriter{
    public static void main(String[] args){
        FileWriter writeObj; //declare variables (uninstantiated)
        PrintWriter printObj;
             String myText = "Hello Text file"; 
        try{ //risky behaviour – catch any errors
                writeObj = new FileWriter("C:\\Documents\\myText.txt" , true);
           printObj = new PrintW        


Mohith P February 2016

For reading text from a file

    FileReader fr = new FileReader("YourFile.txt");
            BufferedReader br = new BufferedReader(fr);
            String s="";

For Writting Text to file

PrintWriter writeText = new PrintWriter("YourFile.txt", "UTF-8");
        writeText.println("The first line");
        writeText.println("The second line");

Post Status

Asked in February 2016
Viewed 2,004 times
Voted 9
Answered 1 times


Leave an answer

Quote of the day: live life