I was given a programming exercise which calls to: "Write a program to create a file named Exercise09_19.txt if it does not exist. Write 100 integers created randomly into the file using text I/O. Integers are separated by spaces in the file. Read the date back from the file and display the sorted data.

Look, I am not asking someone to do the assignment form me, but I can't, for the life of me, figure out how to store the random integers in the file and then read them back. I can create 100 random integers easily, and sorting them should be no problem but my book has too little information on the topic of reading and writing through text I/O!

PLEASE HELP ME WITH THE PROPER WAY TO STORE THE INTEGERS AND THEN READ THEM OUT OF A FILE, THROUGH THE USE OF TEXT I/O!

I realize no body want to write some one else's code but I'm in dire straights here. I need an example, or something, of how information is put into an IO file and then read out. I'm not asking for my program to be completed for me.

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class Exercise09_19 {

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

        java.io.File file1 = new java.io.File("Exercise09_19.txt");
        if (file1.exists()) {
            System.out.println("File Already exists.");

            System.exit(0);
        }
        
        for (int i = 0; i < 100; i++) {
            int x = (int) (Math.random() * 100);
            //what do I do with this to get it into an IO file
        }
        
               
    }
}

Dani AI

Generated

A simple way to meet the assignment is: write the numbers as plain text (separated by single spaces), then let Scanner read them back as integers, sort, and print. Building on and , you can avoid manual split and messy close logic by using try-with-resources and PrintWriter/Scanner. Also note is right that you still need to sort after reading.

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

public class Exercise09_19 {
    public static void main(String[] args) throws Exception {
        // 1) generate 100 random ints in [0, 100)
        int[] nums = new int[100];
        Random r = new Random();
        for (int i = 0; i < nums.length; i++) nums[i] = r.nextInt(100);

        // 2) write them as text, separated by spaces
        try (PrintWriter out = new PrintWriter(new FileWriter("Exercise09_19.txt"))) {
            for (int i = 0; i < nums.length; i++) {
                if (i > 0) out.print(' ');
                out.print(nums[i]);
            }
        }

        // 3) read them back
        List<Integer> values = new ArrayList<>();
        try (Scanner sc = new Scanner(new File("Exercise09_19.txt"))) {
            while (sc.hasNextInt()) values.add(sc.nextInt());
        }

        // 4) sort and display
        int[] data = new int[values.size()];
        for (int i = 0; i < data.length; i++) data[i] = values.get(i);
        Arrays.sort(data);

        for (int i = 0; i < data.length; i++) {
            if (i > 0) System.out.print(' ');
            System.out.print(data[i]);
        }
        System.out.println();
    }
}

Notes:

  • Scanner splits on any whitespace by default, so you do not need to parse lines or call split.
  • PrintWriter(new FileWriter(...)) creates the file if it does not exist and overwrites if it does. If your requirement is to only create when absent, first check new File("Exercise09_19.txt").exists() and decide whether to exit or choose a new filename.
  • On Java 6, replace try-with-resources with the explicit try/finally close style shown by .

Recommended Answers

All 7 Replies

When you want to read from or write to a file in Java you have to use different streams depending on what kind of file it is. You also have to take care of exceptions that can be thrown.
I hope this link will help you:

I want you to look at post #3 in this thread. There is an example of a filehandler and the part that should be of interest for you is how to read and write from/to a textfile. This is of course if you decide to store your numbers in an array, which is the easiest way in my opinion. You can also store them as objects in a vector, but that would be a bit overkill.
The code is written by me (you can find similar examples by googling on filehandler) so you can use those parts you want as long as you are sure that you understand what is happening in the code.You should also read more in Java API and Java tutorials.

Good luck :)

For writing I use this:
BufferedWriter, FileWriter:

BufferedWriter wr = null;
try {
   wr = new BufferedWriter(new FileWriter("Exercise09_19.txt"));

   wr.write("something");
} catch (Exception e) {
  System.out.println(e.getMessage());
} finally {
  if (wr!=null) wr.close();
}

The BufferedWriter is declared outside the try, in order to be "visible" in the finally when we close it. But initialized in the try because it throws an exception. Since the close also throws an exception, you should try this:

BufferedWriter wr = null;
try {
   wr = new BufferedWriter(new FileWriter("Exercise09_19.txt"));

   wr.write("something");
} catch (Exception e) {
  System.out.println(e.getMessage());
} finally {
  try {if (wr!=null) wr.close();} catch (Exception e) {}
}

Write to the file and then review it. I would suggest to put wr.write("something") in your loop. Meaning that all your loop would be in the try - catch.

Following javaAddict's code, I have replaced the BufferedWriter and FileWriter with BufferedReader and FileReader. In order to get each integer value back, the method of class String split is given the delimiter of a space " ". Please read the method of String split(...) in API. Therefore, for reading the existing file I would like to use the following code. Of course, xterradaniel, you have to parse each token into int type.

BufferedReader rd = null;
	try {
   		rd = new BufferedReader(new FileReader("Exercise09_19.txt"));
		String s="";
		
		while( (s=rd.readLine()) != null){
			String ss[]=s.split(" "); // set up the delimiter as space " "
			for (int i=0; i<ss.length;i++)
		    System.out.print(ss[i] + " ");// The string/token array is printed
		}
		
	} catch (Exception e) {
  	System.out.println(e.getMessage());
	} finally {
	  try {if (rd!=null) rd.close();} catch (Exception e) {}
	}

Solution of you proble is:

import java.io.*;

public class file {
    public static void main(String ar[]) {
        int x=0;
        try {
            File file=new File("abc1276.txt");
            FileWriter filewriter=new FileWriter(file);
            BufferedWriter writer=new BufferedWriter(filewriter);

            for(int i=0;i<10;i++) {
                x=(int)(Math.random()*10+10);
                writer.write(" "+x);
            }
            writer.close();
        }
        catch(IOException e) {
            e.printStackTrace();
        }
        try {
            File file1=new File("abc1276.txt");
            FileReader filereader=new FileReader(file1);
            BufferedReader reader=new BufferedReader(filereader);
            String y;
            while((y=reader.readLine())!=null) {
                System.out.println(y);
            }
        }
        catch(Exception e) {
            e.printStackTrace();
        }



    }

}

Solution of you proble is:

import java.io.*;

public class file {
    public static void main(String ar[]) {
        int x=0;
        try {
            File file=new File("abc1276.txt");
            FileWriter filewriter=new FileWriter(file);
            BufferedWriter writer=new BufferedWriter(filewriter);

            for(int i=0;i<10;i++) {
                x=(int)(Math.random()*10+10);
                writer.write(" "+x);
            }
            writer.close();
        }
        catch(IOException e) {
            e.printStackTrace();
        }
        try {
            File file1=new File("abc1276.txt");
            FileReader filereader=new FileReader(file1);
            BufferedReader reader=new BufferedReader(filereader);
            String y;
            while((y=reader.readLine())!=null) {
                System.out.println(y);
            }
        }
        catch(Exception e) {
            e.printStackTrace();
        }



    }

}

Thanks, I really appreciate the assistance. I finally got it working with your help.

though printed back integers are not sorted

if anyones looking at this and still needs sorting you can use:

package drawFramePackage;
import java.awt.geom.AffineTransform;
import java.util.ArrayList;
import java.util.ListIterator;
import java.util.Random;
public class QuicksortAlgorithm {
    ArrayList<AffineTransform> affs;
    ListIterator<AffineTransform> li;
    Integer count, count2;
    /**
     * @param args
     */
    public static void main(String[] args) {
        new QuicksortAlgorithm();
    }
    public QuicksortAlgorithm(){
        count = new Integer(0);
        count2 = new Integer(1);
        affs = new ArrayList<AffineTransform>();
        for (int i = 0; i <= 128; i++){
            affs.add(new AffineTransform(1, 0, 0, 1, new Random().nextInt(1024), 0));
        }
        affs = arrangeNumbers(affs);
        printNumbers();
    }
    public ArrayList<AffineTransform> arrangeNumbers(ArrayList<AffineTransform> list){
        while (list.size() > 1 && count != list.size() - 1){
            if (list.get(count2).getTranslateX() > list.get(count).getTranslateX()){
                list.add(count, list.get(count2));
                list.remove(count2 + 1);
            }
            if (count2 == list.size() - 1){
                count++;
                count2 = count + 1;
            }
            else{
            count2++;
            }
        }
        return list;
    }
    public void printNumbers(){
        li = affs.listIterator();
        while (li.hasNext()){
            System.out.println(li.next());
        }
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.