Google Answers Logo
View Question
 
Q: I/O in java, i guess? ( Answered 5 out of 5 stars,   1 Comment )
Question  
Subject: I/O in java, i guess?
Category: Computers > Programming
Asked by: rejct-ga
List Price: $5.00
Posted: 11 Jun 2003 22:39 PDT
Expires: 11 Jul 2003 22:39 PDT
Question ID: 216338
two part question
in Java, if i created a list of random numbers say 1-5 all unique.
how would i save the output to a text file
(exp of out put)
5(*the first entry is the amout of integers)
1
3
4
5
2
...what i want to do is save that output to a .txt file how would i do
that

second part of the question
im building a heap.... i want to use the first number of that list as
the size of the heap and then fill it in with the remaing integers.my
problem is that i cant figure out how to read the .txt so that  i can
use those numbers to fill in what i have...

if you need more clarification ask... im not asking how to implement
the heap!
im just asking how to output the list to a .txt and then use the list
in another program.
i would then need to read in that text
Answer  
Subject: Re: I/O in java, i guess?
Answered By: answerguru-ga on 12 Jun 2003 10:36 PDT
Rated:5 out of 5 stars
 
Greetings rejct-ga,

Based on your question, it seems you are looking to get some insight
into how Java writes to a file and reads files.

WRITING TO A FILE

// Begin sample file writing code

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

	// creates a FileWriter object that will write to filename.txt
	// second parameter is a boolean that will append new values to the
file

FileWriter fw = new FileWriter("filename.txt", true);

	// PrintWriter uses the FileWriter object to output data

PrintWriter pw = new PrintWriter(fw);

	// writing a value to file on a new line

int myValue = 432;
pw.println(myValue);

// End sample code


READING FROM A FILE

// Begin sample file writing code

import java.io.FileReader;
import java.io.BufferedReader;

	// creates a FileReader object that reads from filename.txt

FileReader fr = new FileReader("filename.txt");

	// BufferedReader uses FileReader to retrieve file contents

BufferedReader br = new BufferedReader(fr);

	// reads in the next line from the file

String lineOne = br.readLine();
	
	//  converts the String to an int
try
{
	int lineOneIntValue = Integer.parseInt(lineOne);
}
catch(NumberFormatException n) 
{
	System.out.println("NumberFormatException: " + n.getMessage());
}

// end sample code


Of course the code snippets above just exhibit how these I/O classes
can be used for simple read and write operations with files, but you
can get into some pretty obscure things if you need to :)

You can read more about the IO classes used in the sample at the Java
Sun site:

http://java.sun.com/j2se/1.3/docs/api/java/io/FileWriter.html

http://java.sun.com/j2se/1.3/docs/api/java/io/PrintWriter.html

http://java.sun.com/j2se/1.3/docs/api/java/io/FileReader.html

http://java.sun.com/j2se/1.3/docs/api/java/io/BufferedReader.html


If you have any problems understanding the information above please do
post a clarification and I will respond promptly.

Cheers!

answerguru-ga

Request for Answer Clarification by rejct-ga on 12 Jun 2003 12:49 PDT
i want to read 10,000 random numbers to a text file how would i do
that
when i create the file writer it throws back a null page... 
what i want is to convert the out-put of this code to a text file:
im using Sun j2sdk1.4.1 and running it through DOS. what i cant figure
out how to do is to save the output to a .txt file, when i want
another program to read the data and place it into an array

import java.math.*;

public class RandomIntegerGenerator{
    int min = 0;
    int max = 5;
    int numberToGenerate = 5;

    public static void main(String[] args){
        RandomIntegerGenerator generator = new
RandomIntegerGenerator();
        int[] uniqueIntegers = generator.generate();
             System.out.println("5");
        for (int i = 0; i < uniqueIntegers.length; i++){
            System.out.println(uniqueIntegers[i]);
        }
    }

    public int getMinimum(){
        return min;
    }

    public int getMaximum(){
        return max;
    }

    public int getNumberToGenerate(){
        return numberToGenerate;
    }

    public void setMinimum(int min){
        this.min = min;
    }

    public void setMaximum(int max){
        this.max = max;
    }

    public void setNumberToGenerate(int numberToGenerate){
        this.numberToGenerate = numberToGenerate;
    }


    public int[] generate(){
        int[] numbers = new int[getNumberToGenerate()];
        for (int i = 0; i < numbers.length; i++){
            boolean uniqueNewIntegerFound = false;
            int newInteger = min -1;
            while (!uniqueNewIntegerFound){
                newInteger = getRandomInteger();
                boolean isUsed = false;
                for (int j = 0;j <= i; j++){
                    if (numbers[j] == newInteger) isUsed = true;
                }
                if (!isUsed) {
                    uniqueNewIntegerFound = true;
                    numbers[i] = newInteger;
                }
            }
        }
        return numbers;
    }

    private int getRandomInteger(){
        double randomNumber = Math.random();
        randomNumber = randomNumber * (double)(max - min + 1);
        return (int)randomNumber;
    }

}

Clarification of Answer by answerguru-ga on 12 Jun 2003 13:21 PDT
Hi again,

I believe I missed two lines for the writer section:

fw.close();
pw.close();

This line closes the file, so your changes in the program will be
reflected appropriately.

From the code you provided, I have added the writing function (only
the main method needs updating based on what you have provided:

// need to add import of IO package
import java.io.*;

// modified main method

public static void main(String[] args)
{ 
        RandomIntegerGenerator generator = new
RandomIntegerGenerator();
	FileWriter fw = new FileWriter("output.txt");
	PrintWriter pw = new PrintWriter(fw);

        int[] uniqueIntegers = generator.generate(); 

        pw.println("5"); 
        
	for (int i = 0; i < uniqueIntegers.length; i++)
	{ 
            pw.println(uniqueIntegers[i]); 
        } 

	fw.close();
	pw.close();
} 


This code above will create a new file, output.txt, then prints the
value "5" on the first line followed by values taken from the int[] on
subsequent lines.

When you are reading back the data from the file, use the sample code
from the READER section in the original answer.

Hope that helps,

answerguru-ga

Request for Answer Clarification by rejct-ga on 12 Jun 2003 13:37 PDT
also the reader sample reads the first line, how would i read the other lines

Clarification of Answer by answerguru-ga on 12 Jun 2003 14:19 PDT
You just need to keep calling br.readLine() where appropriate and
retrieving the String that is returned. The class keeps track of where
you are in the file and just moves down one line each time. At the
last line you will retrieve a null value, which will tell you that you
have reached the end of the file.

It seems that for your purpose a loop would do the trick :)

answerguru-ga

Request for Answer Clarification by rejct-ga on 12 Jun 2003 15:41 PDT
in the main section i am getting errors... any ideas on how to correct the problem
C:\WINDOWS>cd c:\java

C:\java>c:\sdk\bin\javac RandomIntegerGenerator.java
RandomIntegerGenerator.java:24: unreported exception java.io.IOException; must b
e caught or declared to be thrown
 FileWriter fw = new FileWriter("output.txt");
                 ^
RandomIntegerGenerator.java:36: unreported exception java.io.IOException; must b
e caught or declared to be thrown
 fw.close();
   ^
2 errors

C:\java>

Clarification of Answer by answerguru-ga on 12 Jun 2003 15:47 PDT
Yes, you need to surround all of the code in your main by a try/catch block:

try
{
  // all your code here
}
catch(IOException io){}
rejct-ga rated this answer:5 out of 5 stars
very fast very helpful

Comments  
Subject: Re: I/O in java, i guess?
From: secret901-ga on 11 Jun 2003 23:11 PDT
 
Hi rejct-ga,
You can take a look at the classes FileReader and FileWriter found
here: http://www.ics.uci.edu/~dhnguyen/FileExtraction/
They provide useful interfaces to read from files and write to files.
Hope that helps,
secret901-ga

Important Disclaimer: Answers and comments provided on Google Answers are general information, and are not intended to substitute for informed professional medical, psychiatric, psychological, tax, legal, investment, accounting, or other professional advice. Google does not endorse, and expressly disclaims liability for any product, manufacturer, distributor, service or service provider mentioned or any opinion expressed in answers or comments. Please read carefully the Google Answers Terms of Service.

If you feel that you have found inappropriate content, please let us know by emailing us at answers-support@google.com with the question ID listed above. Thank you.
Search Google Answers for
Google Answers  


Google Home - Answers FAQ - Terms of Service - Privacy Policy