Generated integers to a binary file - java

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(); } }

Related

implement sorting in java for file with records

I asked this question earlier and I forgot to clarify what my question was so hopefully I'm actually clear this time.
I basically need help with sorting a bunch of records in a file based on their number using an algorithm like bubble sort.
I have a file with 5 records where each file consists of a number of integer type and name of 32 characters(each record size should be 36 bytes). I have to store the records into a file. **This is what I need help with:**Then sort the records based on the numbers associated with them, using a sorting algorithm like bubble sort. Another requirement is that when the program sorts the records, it shouldn't read all records in memory at once but move them in the file. For example, after the program reads the first two records, it may switch the records (because 72 > 56) and write them in the same position in the file.
We were provided with the classes to read/write and have random access to the file.
These are the records as they were provided:
72 James
56 Mark
87 John
30 Phillip
44 Andrew
I need to sort these names according to their respective numbers. My question is, what would be the best way to implement this sorting?
Here's the code for the writing class:
package test;
//write to a file
import java.io.*;
class FileWriteStreamTest {
public static void main (String[] args) {
FileWriteStreamTest f = new FileWriteStreamTest();
f.writeMyFile();
}
void writeMyFile() {
DataOutputStream dos = null;
String record = null;
int recCount = 0;
try {
File f = new File("mydata.txt");
if (!f.exists())
f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);
BufferedOutputStream bos = new BufferedOutputStream(fos);
dos = new DataOutputStream(bos);
//store records into file
dos.writeBytes(72 + " James \n");
dos.writeBytes(56 + " Mark \n");
dos.writeBytes(87 + " John \n");
dos.writeBytes(30 + " Phillip \n");
dos.writeBytes(44 + " Andrew \n");
} catch (IOException e) {
System.out.println("Uh oh, got an IOException error!" + e.getMessage());
} finally {
// if the file opened okay, make sure we close it
if (dos != null) {
try { dos.close(); }
catch (IOException ioe) { }
}
}
}
}
Here's the code for the reading class:
package test;
//read from a file
import java.io.*;
public class FileReadStreamTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
FileReadStreamTest f = new FileReadStreamTest();
f.readMyFile();
}
void readMyFile() {
DataInputStream dis = null;
String record = null;
int recCount = 0;
try {
File f = new File("mydata.txt");
if (!f.exists()) {
System.out.println(f.getName() + " does not exist");
return;
}
FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while ( (record=dis.readLine()) != null ) {
recCount++;
System.out.println(recCount + ": " + record);
}
} catch (IOException e) {
System.out.println("Uh oh, got an IOException error!" + e.getMessage());
} finally {
// if the file opened okay, make sure we close it
if (dis != null) {
try { dis.close(); }
catch (IOException ioe) { }
}
}
}
}
Here's the code for the random access class:
package test;
//read or write to any place in the file
import java.io.*;
class FileRandomAccessTest {
public static void main (String[] args) {
FileRandomAccessTest f = new FileRandomAccessTest();
f.readWriteMyFile();
}
void readWriteMyFile() {
RandomAccessFile raf = null;
String s = null;
try {
File f = new File("mydata.txt");
if (!f.exists()) // check if the file exists
f.createNewFile(); // create a new file
raf = new RandomAccessFile(f, "rw"); // open a file for random access with "r", "rw"
if (raf.length() > 7) {// the size of the file
raf.seek(7); // move the file pointer
System.out.println(raf.readLine()); // read a line from the file pointer
s = raf.readLine();
System.out.println(s);
raf.seek(raf.getFilePointer() - s.length()); // get the file pointer
raf.writeBytes("Test RamdomAccessFile\n"); // write bytes
}
} catch (IOException e) {
System.out.println("Uh oh, got an IOException error!" + e.getMessage());
} finally {
// if the file opened okay, make sure we close it
if (raf != null) {
try { raf.close(); } // close the file
catch (IOException ioe) { }
}
}
}
}
My current bubble sort implementation that needs to be adapted for this problem:
package test;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class Sort {
public static void bubbleSort(int[] num ) {
int j;
boolean flag = true; // set flag to true to begin first pass
int temp; //holding variable
while ( flag ) {
flag= false; //set flag to false awaiting a possible swap
for( j=0; j < num.length -1; j++ ) {
if ( num[ j ] < num[j+1] ) {
temp = num[ j ]; //swap elements
num[ j ] = num[ j+1 ];
num[ j+1 ] = temp;
flag = true; //shows a swap occurred
}
}
}
}
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("numbers.txt"));
int [] numbers = new int [5];
int i = 0;
while(scanner.hasNextInt()){
numbers[i++] = scanner.nextInt();
}
bubbleSort(numbers);
System.out.println(Arrays.toString(numbers));
}
}

Why is the smallest number read from my file always 0? (Java)

When I run the program, the smallest number always turns out to be 0. Why is this? The largest and average values seem to be correct.
The problem most likely lies in how I am using the random class.
import java.io.*;
import java.util.*;
import java.util.Arrays;
public class ReadAndWrite {
public static void main(String[] args) {
Random ran = new Random();
int i_data = 0;
int[] sort = new int[100];
File file = new File("Test4");
int total = 0;
int average = 0;
try {
file.createNewFile();
}
catch(Exception e) {
System.out.println("Could not create the file for some reason. Try again.");
System.exit(0);
}
try {
FileOutputStream fos = new FileOutputStream("Test4");
ObjectOutputStream oos = new ObjectOutputStream(fos);
for(int i = 0; i <= 100; i++) {
int x = ran.nextInt(100);
oos.writeInt(x);
}
oos.close();
}
catch(IOException e) {
System.out.println("Whoops");
}
try {
FileInputStream fos = new FileInputStream("Test4");
ObjectInputStream ooss = new ObjectInputStream(fos);
for (int i = 0; i < 100; i++) {
sort[i] = ooss.readInt();
}
Arrays.sort(sort);
for(int i = 0; i < 100; i++) {
total = total + sort[i];
average = total/100;
}
System.out.println("The largest number in the file is: " + sort[99]);
System.out.println("The smallest number in the file is: " + sort[0]);
System.out.println("The average number in the file is: " + average);
ooss.close();
}
catch(Exception e) {
System.out.println(e);
}
}
}
You are sorting the array as you read each value.
for(int i = 0; i < 100; i++) {
sort[i] = ooss.readInt();
Arrays.sort(sort);
}
This means you start with [1, 0, 0, 0, ...] but after sorting you have [0, 0, 0, ... 1 ]
This is where a debugger would help you debug your program. The solution is to only sort the array after you have read it.
A simpler solution is to write and read the array in one go instead of using a loop.
BTW: Unless you are writing/reading objects you don'#t need to be using ObjectOutputStream and it has an overhead compared with say DataOutputStream.
As #KevinEsche points out, if you have 100 random values of 0 to 99 there is a good chance that one of them will be 0, though not every time.
A shorter implementation could look like this
public static void main(String[] args) throws IOException {
Random rand = new Random();
int samples = 100;
try (DataOutputStream out = new DataOutputStream(new FileOutputStream("test"))) {
out.writeInt(samples);
for (int i = 0; i < samples; i++)
out.writeInt(rand.nextInt(100));
}
int[] sort;
try (DataInputStream in = new DataInputStream(new FileInputStream("test"))) {
int len = in.readInt();
sort = new int[len];
for (int i = 0; i < len; i++)
sort[i] = in.readInt();
}
IntSummaryStatistics stats = IntStream.of(sort).summaryStatistics();
System.out.println("The largest number in the file is: " + stats.getMax());
System.out.println("The smallest number in the file is: " + stats.getMin());
System.out.println("The average number in the file is: " + stats.getAverage());
}

How can I make this Java read the whole last line, and not just each byte at a time?

I have a simple Java IO program which reads from a text file of numbers that looks like this :
1
2
3
4
5
6
7
8
9
17
It's supposed to simply print the lines in this text file to the console, and then tell me what the last line was. But it's printing the last line, here 17, as just 7 -
Here's my code so far :
import java.lang.*;
import java.io.*;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ParentClass3{
static int lastLine = 0;
public static void main(String[] args) {
File file = new File("C:\\Java_Scratch_\\someFile.txt");
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
try {
int i = sc.nextInt();
System.out.println(i);
} catch (Exception e) {
System.out.println (" here is the stack trace " + e.getStackTrace() );
System.out.println (" here is the stack trace " );
}
}
sc.close();
} // END big-outer-Try
catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
int i = ParentClass3.countLines("C:\\Java_Scratch_\\someFile.txt");
System.out.println("There are " + i + " lines");
}
catch (IOException ioe) {
System.out.print("ioe" + ioe.getStackTrace() );
}
}
// putting the count function
public static int countLines(String filename) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try {
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
int lastline = 0;
boolean empty = true;
while ( (readChars = is.read(c)) != -1) {
for (int i = 0; i < readChars; ++i){
Byte b = c[i];
int xx = b.intValue();
lastLine = xx;
if (c[i] == '\n'){
++count;
empty = true;
} else {
empty = false;
}
}
}
if (!empty) {
count++;
}
int asciiVal = lastLine;
int lastLine2 = Character.getNumericValue(asciiVal);
System.out.println("the last line was " + lastLine2);
return count;
} finally {
is.close();
}
}//END method countLines
// end-count_func
}
How would I fix it, so that it says "the last line was 17" , rather just just 7 ?
the methos nextLine() should work, although I don't remember if that input would be parsed to a String, I guess that wouldn't affect, but anyway...

Input / Output 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();
}

Reading File into a char[] array or arraylist

I need to read text from the user and create an array which contains characters so that I can run them through a FSM. However, I can't seem to get the buffered reader to agree with a non-string type of input. Any advice? I also don't know if I should be using an array or arraylist
static ArrayList<Character> StringList = new ArrayList<Character>();
static char[] data;
public static void main(String[] args){
InputStreamReader ISR = new InputStreamReader (System.in);
BufferedReader BR = new BufferedReader(ISR);
try{
String sCurrentChar;
while((sCurrentChar=BR.readLine())!=null){
for(int i= 0; i<sCurrentChar.length(); i++)
StringList.add(sCurrentChar.charAt(i));
}
for(int i =0; i<StringList.size(); i++){
System.out.println(StringList.get(i));
}
} catch(IOException e){
e.printStackTrace();
}
}
Maybe something like the following could work for you, if you want to read raw byte data, maybe using them later as characters. This might be a better approach than reading input line at a time.
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.util.Arrays;
public class a {
public static void main(String[] args){
DataInputStream d = new DataInputStream(System.in);
int[] bytes = new int[256];
try {
int b;
int l = 0;
while((b = d.readByte()) > 0) {
bytes[l++] = b;
if((l % 256) == 0)
bytes = Arrays.copyOf(bytes, (l + 256));
}
} catch(EOFException e) {
// end-of-file
} catch(IOException e) {
System.err.println("AIEEEE: " + e);
System.exit(-1);
}
for(int i = 0; bytes[i] > 0; i++) System.out.print((char)bytes[i]);
System.exit(0);
}
}
The way arrays are treated here is probably a fine example how one should not do it, but then again, this is more about reading bytes/unsigned characters of data than efficiently processing arrays.

Categories

Resources