Input / Output Java - java

My program is supposed to write 100 random integers on a text file and read them. The problem is that I'm only printing 1 integer. I know I'm close. What am I doing wrong?
import java.util.Random;
public class WriteData {
public static void main(String[] args) throws Exception {
//create a file instance
java.io.File file = new java.io.File("random100.txt");
if (file.exists()) {
System.out.println("File already exists");
System.exit(0);
}
//create a file
java.io.PrintWriter output = new java.io.PrintWriter(file);
//write formatted output to the file
Random randomGenerator = new Random();
for (int idx = 1; idx <= 100; ++idx) {
int randomInt = randomGenerator.nextInt(100);
output.print(randomGenerator);
//log("Generated : " + randomInt);
//close file
output.close();
}
}
}
import java.util.Scanner;
public class ReadData {
public static void main(String[] args) throws Exception {
//create file instance
java.io.File file = new java.io.File("random100.txt");
//create a scanner for the file
Scanner input = new Scanner(file);
//read data from a file
while (input.hasNext()) {
int number = input.nextInt();
System.out.println(number + " ");
}
//close file
input.close();
}
}

output.close(); should be outside the for loop. Right now, the loop just executes once and the outputStream gets closed. Hence, you get just one number.

You are closing your output INSIDE your for, move it outside. (print randomInt not randomGenerator also)
public static void main(String[] args)throws Exception {
//create a file instance
java.io.File file = new java.io.File("random100.txt");
if(file.exists()){
System.out.println("File already exists");
System.exit(0);
}
//create a file
java.io.PrintWriter output = new java.io.PrintWriter(file);
//write formatted output to the file
Random randomGenerator = new Random();
for (int 0 = 1; idx < 100; ++idx){
int randomInt = randomGenerator.nextInt(100);
output.print(randomInt);
}
//close file
output.close();
}

Related

Trying to read from a binary file to an array

I'm working on a school assignment, the requirements are as follows: "Design a class that has a static method named writeArray. The method should take two arguments: the name of the file and a reference to an int array. The file should be opened as a binary file, the contents of the array should be written to the file, then the file should be closed. Write a second method in the class named readArray. The method should take two arguments: the name of a file, and a reference to an int array. The file should be opened, data should be read from the file and stored in the array, then the file should be closed. Demonstrate both methods in a program."
Here's my code so far for the class and demo:
import java.io.*;
public class FileArray
{
public static void writeArray(String filename, int[] array) throws IOException
{
//Open the file.
DataOutputStream outputFile = new DataOutputStream(new FileOutputStream("MyNumbers.txt"));
//Write the array.
for(int index = 0; index < array.length; index++)
{
outputFile.writeInt(array[index]);
}
//Close the file.
outputFile.close();
}
public static void readArray(String filename, int[] array) throws IOException
{
int number;
boolean endOfFile = false;
//Open the file.
FileInputStream fstream = new FileInputStream("MyNumbers.txt");
DataInputStream inputFile = new DataInputStream(fstream);
//Read values from the array.
while (!endOfFile)
{
try
{
number = inputFile.readInt();
}
catch (EOFException e)
{
endOfFile = true;
}
}
//Close the file.
inputFile.close();
}
}
Second class:
import java.io.*;
public class FileArrayDemo extends FileArray
{
public static void main(String[] args)
{
//Create arrays.
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8};
int[] test = new int[8];
//Try/catch clause.
try
{
//Write the contents of the numbers array to the file MyNumbers.txt.
FileArray fileArray = new FileArray();
fileArray.writeArray("MyNumbers.txt", numbers);
//Read the contents of the file MyNumbers.txt into the test array.
fileArray.readArray("MyNumbers.txt", test);
//Display the numbers from the test array.
System.out.println("The numbers read from the file are:");
for (int i = 0; i < test.length; i++)
System.out.print(test[i] + " ");
}
catch (IOException e)
{
System.out.println("Error = " + e.getMessage());
}
}
}
When I try to use the demo file, my array is showing all 0's instead of numbers 1-8. I'm not sure what I'm doing wrong here at all. I've been following along with the examples from my book, but they only provide demonstrations in one class instead of having a class that creates methods to perform the write/read operations.
You need just to modify the array passed in parameters, your readArray function is just read and does not modify the array.
try ramplacing your readArray function by this one:
public static void readArray(String filename, int[] array) throws IOException{
int number;
boolean endOfFile = false;
//Open the file.
FileInputStream fstream = new FileInputStream("MyNumbers.txt");
DataInputStream inputFile = new DataInputStream(fstream);
//Read values from the array.
int i = 0;
while (!endOfFile){
try{
number = inputFile.readInt();
array[i] = number;
i++;
}catch (EOFException e)
{
endOfFile = true;
}
}
//Close the file.
inputFile.close();
}
result :
The numbers read from the file are:
1 2 3 4 5 6 7 8

I am trying to print a 2D array to a file

I want to print 2D array to txt file on my desktop. It is important, that the output is formatted in way, that is in code, because it represents rows and seats.
Code:
package vaja15;
import java.util.*;
import java.io.PrintWriter;
import java.io.File;
import java.io.FileNotFoundException;
public class Vaja15
{
public static void main(String[] args) throws FileNotFoundException
{
System.out.println("Vnesi velikost dvorane (vrste/sedezi): ");
Scanner sc = new Scanner(System.in);
Random r = new Random();
int vrst = sc.nextInt();
int sedezev = sc.nextInt();
int [][] dvorana = new int [vrst][sedezev];
File file = new File ("C:/users/mr/desktop/dvorana.txt");
for(int i = 0; i<dvorana.length; i++)
{
System.out.println();
for (int j = 0; j<dvorana.length; j++)
{
dvorana [i][j] = r.nextInt(3);
System.out.print(dvorana[i][j]);
PrintWriter out = new PrintWriter(file);
out.println(dvorana[i][j]);
out.close();
}
}
}
}
You should not open and close a file in your loop: open a file before the loop, write your array, close the file. Otherwise it will overwrite the file over and over again.
Try this:
PrintWriter out = new PrintWriter(file);
for(int i = 0; i<vrst; i++)
{
System.out.println();
out.println();
for (int j = 0; j<sedezev; j++)
{
dvorana [i][j] = r.nextInt(3);
System.out.print(dvorana[i][j]);
out.print(dvorana[i][j]);
}
}
out.close();
Try the following idea:
try {
File file = new File(path);
FileWriter writer = new FileWriter(file);
BufferedWriter output = new BufferedWriter(writer);
for (int[] array : matrix) {
for (int item : array) {
output.write(item);
output.write(" ");
}
output.write("\n");
}
output.close();
} catch (IOException e) {
}

how to add string read from file to an ArrayList?

I have a super beginner's question. I have a computer science test today and one of the practice problems is this:
Write a program that carries out the following tasks:
Open a file with the name hello.txt.
Store the message “Hello, World!” in the file.
Close the file.
Open the same file again.
Read the message into a string variable and print it.
This is the code I have for it so far:
import java.util.*;
import java.io.*;
public class ReadFile
{
public static void main(String[] args) throws FileNotFoundException
{
PrintWriter out = new PrintWriter("hello.txt");
out.println("Hello, World");
File readFile = new File("hello.txt");
Scanner in = new Scanner(readFile);
ArrayList<String> x = new ArrayList<String>();
int y = 0;
while (in.hasNext())
{
x.add(in.next());
y++;
}
if (x.size() == 0)
{
System.out.println("Empty.");
}
else
{
System.out.println(x.get(y));
}
in.close();
out.close();
}
}
What's wrong with this code?
1) You need to close the stream
2) You need to refer to the x Arraylist with (y-1) otherwise you will get
a java.lang.IndexOutOfBoundsException . The indexes starts from 0 and not from 1.
http://www.tutorialspoint.com/java/util/arraylist_get.htm
public static void main(String[] args) throws FileNotFoundException
{
PrintWriter out = new PrintWriter("hello.txt");
out.println("Hello, World");
out.close();
File readFile = new File("hello.txt");
Scanner in = new Scanner(readFile);
ArrayList<String> x = new ArrayList<String>();
int y = 0;
while (in.hasNext())
{
x.add(in.next());
y++;
}
in.close();
if (x.size() == 0)
{
System.out.println("Empty.");
}
else
{
System.out.println(x.get(y-1));
}
}
}
I guess what's wrong with the code ist that you cant read anything from the file.
this is because PrintWriter is buffered
fileName - The name of the file to use as the destination of this writer. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.
You need to close the file you have just writen to before openning it for reading so that the changes are fluched to the physical storage. Thus moving out.close(); right after out.println("Hello, World");
class FileWritingDemo {
public static void main(String [] args) {
char[] in = new char[13]; // to store input
int size = 0;
try {
File file = new File("MyFile.txt"); // just an object
FileWriter fw = new FileWriter(file); // create an actual file & a FileWriter obj
fw.write("Hello, World!"); // write characters to the file
fw.flush(); // flush before closing
fw.close(); // close file when done
FileReader fr = new FileReader(file); // create a FileReader object
size = fr.read(in); // read the whole file!
for(char c : in) // print the array
System.out.print(c);
fr.close(); // again, always close
} catch(IOException e) { }
}
}

calling method with IOException

I had this program with which i have to check if the value the user entered is present in the text file i created in the source file. However it throws me an error everytime i try to call the method with IOException. Please help me out thanks.
import java.util.*;
import java.io.*;
public class chargeAccountModi
{
public boolean sequentialSearch ( double chargeNumber ) throws IOException
{
Scanner keyboard= new Scanner(System.in);
int index = 0;
int element = -1;
boolean found = false;
System.out.println(" Enter the Charge Account Number : " );
chargeNumber = keyboard.nextInt();
int[] tests = new int[18];
int i = 0;
File file = new File ("Names.txt");
Scanner inputFile = new Scanner(file);
while(inputFile.hasNext() && i < tests.length )
{
tests [i] = inputFile.nextInt();
i++;
}
inputFile.close();
for ( index = 0 ; index < tests.length ; index ++ )
{
if ( tests[index] == chargeNumber )
{
found = true;
element = index;
}
}
return found;
}
public static void main(String[]Args)
{
double chargeNumber = 0;
chargeAccountModi object1 = new chargeAccountModi();
try
{
object1.sequentialSearch(chargeNumber);
}
catch (IOException ioe)
{
}
System.out.println(" The search result is : " + object1.sequentialSearch (chargeNumber));
}
}
After looking on your method sequentialSearch there is everythink ok. But try to change main:
But remember that in your Names.txt file you should have only numbers because you use scanner.nextInt();, so there should be only numbers or method will throw exeption InputMismatchException.
Check also path to Names.txt file you should have it on classpath because you use relative path in code File file = new File ("Names.txt"); Names.txt should be in the same folder.
public static void main(String[]Args)
{
double chargeNumber = 0;
chargeAccountModi object1 = new chargeAccountModi();
try
{
System.out.println(" The search result is : " + object1.sequentialSearch(chargeNumber));
}
catch (IOException ioe)
{
System.out.println("Exception!!!");
ioe.printStackTrace();
}
}
Few tips and suggestions:
First of all: Don't forget to close the Scanner objects! (you left one unclosed)
Second of all: Your main method is highly inefficient, you are using two loops, in the first one you read and store variables, in the second one you check for a match, you can do both at the same time (I've written an alternative method for you)
Third little thing: The variable "element" is not used at all in your code, I've removed it in the answer.
And last but not least: The file "Names.txt" needs to be located (since you've only specificied it's name) in the root folder of your project, since you mention an IOException, I figure that's what's wrong with the app. If your project is called Accounts, then it's a folder called Accounts with it's source and whatever else is part of your project, make sure the file "Accounts/Names.txt" exists! and that it is in the desired format.
import java.util.*;
import java.io.*;
public class ChargeAccountModi {
public boolean sequentialSearch(double chargeNumber) throws IOException {
Scanner keyboard= new Scanner(System.in);
int index = 0;
boolean found = false;
System.out.print("Enter the Charge Account Number: " );
chargeNumber = keyboard.nextInt();
int[] tests = new int[18];
int i = 0;
File file = new File ("Names.txt");
Scanner inputFile = new Scanner(file);
while(inputFile.hasNext() && i < tests.length ) {
tests [i] = inputFile.nextInt();
i++;
}
inputFile.close();
for (index = 0 ; index < tests.length ; index ++ ) {
if (tests[index] == chargeNumber) {
found = true;
}
}
keyboard.close();
return found;
}
public boolean sequentialSearchAlternative(double chargeNumber) throws IOException {
Scanner keyboard= new Scanner(System.in);
boolean found = false;
System.out.print("Enter the Charge Account Number: " );
chargeNumber = keyboard.nextInt();
int tests = 18;
int i = 0;
File file = new File ("Names.txt");
Scanner inputFile = new Scanner(file);
while(inputFile.hasNext() && i<tests) {
if (inputFile.nextInt() == chargeNumber) {
found = true;
break;
}
i++;
}
inputFile.close();
keyboard.close();
return found;
}
public static void main(String[] args) {
double chargeNumber = 0;
ChargeAccountModi object1 = new ChargeAccountModi();
try {
System.out.println("The search result is : " + object1.sequentialSearch(chargeNumber));
} catch (Exception e) {
//Handle the exceptions here
//The most likely exceptions are:
//java.io.FileNotFoundException: Names.txt - Cannot find the file
//java.util.InputMismatchException - If you type something other than a number
e.printStackTrace();
}
}
}

Generated integers to a binary file

I have assignment question I could not get the final answer.
the question was :
Write a program that will write 100 randomly generated
integers to a binary file using the writeInt(int) method in
DataOutputStream. Close the file. Open the file using a
DataInputStream and a BufferedInputStream. Read the integer
values as if the file contained an unspecified number (ignore
the fact that you wrote the file) and report the sum and average
of the numbers.
I believe I done first part of the question which is (write into file), but I don't know how to report the sum.
so far that what I have
import java.io.*;
public class CreateBinaryIO {
public static void main(String [] args)throws IOException {
DataOutputStream output = new DataOutputStream(new FileOutputStream("myData.dat"));
int numOfRec = 0 + (int)(Math.random()* (100 - 0 +1));
int[] counts = new int[100];
for(int i=0;i<=100;i++){
output.writeInt(numOfRec);
counts[i] += numOfRec;
}// Loop i closed
output.close();
}
}
This ReadBinaryIO class:
import java.io.*;
public class ReadBinaryIO {
public static void main(String [] args)throws IOException {
DataInputStream input = new DataInputStream (new BufferedInputStream(new FileInputStream("myData.dat")));
int value = input.readInt();
System.out.println(value + " ");
input.close();
}
}
Try to divide the problem in parts to organice your code, don't forget to flush the OutputStream before you close it.
package javarandomio;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Random;
public class JavaRandomIO {
public static void main(String[] args) {
writeFile();
readFile();
}
private static void writeFile() {
DataOutputStream output=null;
try {
output = new DataOutputStream(new FileOutputStream("myData.txt"));
Random rn = new Random();
for (int i = 0; i <= 100; i++) {
output.writeInt(rn.nextInt(100));
}
output.flush();
output.close();
} catch (Exception e) {
System.out.println(e.getMessage());
} finally{
try{
output.close();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
private static void readFile() {
DataInputStream input=null;
try {
input = new DataInputStream(new FileInputStream("myData.txt"));
int cont = 0;
int number = input.readInt();
while (true) {
System.out.println("cont =" + cont + " number =" + number);
if (input.available() == 4) {
break;
}
number = input.readInt();
cont++;
}
input.close();
} catch (Exception e) {
System.out.println(e.getMessage());
} finally{
try{
input.close();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
}
int numOfRec = 0 + (int)(Math.random()* (100 - 0 +1));
That's not generating a random number. Look into java.util.Random.nextInt().
int[] counts = new int[100];
for(int i=0;i<=100;i++){
output.writeInt(numOfRec);
counts[i] += numOfRec;
}// Loop i closed
That wil actually break because you are using i<=100 instead of just i<100 but I'm not sure why you are populating that array to begin with? Also, that code just writes the same number 101 times. The generation of that random number needs to be within the loop so a new one is generated each time.
As far as reading it back, you can loop through your file by using a loop like this:
long total = 0;
while (dataInput.available() > 0) {
total += dataInput.readInt();
}
Try below code where you are trying to read one integer:
DataInputStream input = new DataInputStream (new BufferedInputStream(new FileInputStream("myData.dat")));
int sum = 0;
for(int i =0; i<=100; i++){
int value = input.readInt();
sum += value;
}
System.out.println(value + " ");
input.close();
Or if you want to dynamically set the lenght of the for loop then
create a File object on myData.dat file and then divide the size of file with 32bits
File file = new File("myData.dat");
int length = file.length() / 32;
for(int i =0; i <= length;i++)
So far I submit the assignment and I think I got.
/** Munti ... Sha
course code (1047W13), assignment 5 , question 1 , 25/03/2013,
This file read the integer values as if the file contained an unspecified number (ignore
the fact that you wrote the file) and report the sum and average of the numbers.
*/
import java.io.*;
public class ReadBinaryIO {
public static void main(String [] args)throws ClassNotFoundException, IOException {
//call the file to read
DataInputStream input = new DataInputStream (new BufferedInputStream(new FileInputStream("myData.dat")));
// total to count the numbers, count to count loops process
long total = 0;
int count = 0;
System.out.println("generator 100 numbers are ");
while (input.available() > 0) {
total += input.readInt();
count ++;
System.out.println(input.readInt());
}
//print the sum and the average
System.out.println("The sum is " + total);
System.out.println("The average is " + total/count);
input.close();
}
}
CreateBinaryIO Class:
import java.io.*; import java.util.Random;
public class CreateBinaryIO { //Create a binary file public static
void main(String [] args)throws ClassNotFoundException, IOException {
DataOutputStream output = new DataOutputStream(new
FileOutputStream("myData.dat"));
Random randomno = new Random();
for(int i=0;i<100;i++){ output.writeInt(randomno.nextInt(100)); }// Loop i closed output.close(); } }

Categories

Resources