Reading a .dat file into an array in Java - java

The code that I'm writing has two classes: writeInts and readInts. I wrote writeInts to randomly generate 100 numbers between 0 and 1000 and output them to a data.dat file.
readInts is supposed to open a DataInputStream object and read in the "raw" data from the data.dat file and store the 100 integers in an array. My problem is that I can't seem to read the data correctly. Any help with this would be greatly appreciated. Thanks!
writeInts:
import java.io.*;
public class WriteInts {
public static void main(String[] args) throws IOException {
DataOutputStream output = new DataOutputStream(new FileOutputStream("data.dat"));
int num = 0 + (int)(Math.random());
int[] counts = new int[100];
for(int i=0; i<100; i++) {
output.writeInt(num);
counts[i] += num;
System.out.println(num);
}
output.close();
}
}
readInts:
import java.io.*;
import java.util.*;
public class ReadInts {
public static void main(String[] args) throws IOException {
// call the file to read
Scanner scanner = new Scanner(new File("data.dat"));
int[] data = new int[100];
int i = 0;
while (scanner.hasNextInt()) {
data[i++] = scanner.nextInt();
System.out.println(data[i]);
scanner.close();
}
}
}

If you want to write binary data, use DataInputStream/DataOutputStream. Scanner is for text data and you can't mix it.
WriteInts:
import java.io.*;
public class WriteInts {
public static void main(String[] args) throws IOException {
DataOutputStream output = new DataOutputStream(new FileOutputStream(
"data.dat"));
for (int i = 0; i < 100; i++) {
output.writeInt(i);
System.out.println(i);
}
output.close();
}
}
ReadInts:
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class ReadInts {
public static void main(String[] args) throws IOException {
DataInputStream input = new DataInputStream(new FileInputStream(
"data.dat"));
while (input.available() > 0) {
int x = input.readInt();
System.out.println(x);
}
input.close();
}
}

More. If you want to generate a random number in range from 0 to 1000 (both inclusive), you use this statement:
int rndNum = (int) (Math.random() * 1001);
It works that way: Math.random() generates a double in range from 0 to 1 (exclusive), which you then should map to integer range and floor. If you want you maximal value to be 1000, you multiply it by 1001 - 1001 itself is excluded.
Yep, like that:
import java.io.*;
public class WriteRandomInts {
public static void main(String[] args) throws IOException {
DataOutputStream output = new DataOutputStream(new FileOutputStream(
"data.dat"));
for (int i = 0; i < 100; i++) {
int rndNum = (int) (Math.random() * 1001);
output.writeInt(rndNum);
System.out.println(rndNum);
}
output.close();
}
}

I'd recommend that you abandon DataInputStream and DataOutputStream.
Write the ints one to a line using FileWriter and read them using a BufferedReader, one per line. This is an easy problem.

Related

How to fix '<identifier> expected' error in HackerRank

I'm new to Java coding, and I'm stuck with a simple ArrayList sum code. I believe that my method is correct, but I don't understand the main method. I tried to run it many times, but it keeps saying that my input, ArrayList ar, is not 'identified'. Help needed!
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
public class Solution {
/*
* Complete the simpleArraySum function below.
*/
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new
FileWriter(System.getenv("OUTPUT_PATH")));
int arCount = Integer.parseInt(scanner.nextLine().trim());
int[] ar = new int[arCount];
String[] arItems = scanner.nextLine().split(" ");
for (int arItr = 0; arItr < arCount; arItr++) {
int arItem = Integer.parseInt(arItems[arItr].trim());
ar[arItr] = arItem;
}
int result = simpleArraySum(ar);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedWriter.close();
}
// Below is my code
public static int simpleArraySum(int n, ar) {
/** It says that 'ar' is not identified. I tried
'Arraylist<Integer>
* ar but it still won't work
int sum = 0;
for (int i = 0; i < ar.size(); i++) {
sum += ar.get(i);
}
return sum;
}
}
This is what it returns:
Compile Message:
Solution.java:39: error: <identifier> expected
public static int simpleArraySum(int n, ar) {
^
1 error
The declaration of type of parameters for the method simpleArraySum is missing.
Try the following signature, it should work
public static int simpleArraySum(int n,int[] ar) {

why isn't the rest of my method being called? (loop being ignored)

i'm trying to write a program that reads a file and then prints it out and then reads it again but only prints out the lines that begin with "The " the second time around. it DOES print out the contents of the file, but then it doesn't print out the lines that begin with "The " and i can't figure out why. it prints out the println line right before the loop, but then it ignores the for-loop completely. the only difference between my findThe method and my OutputTheArray method is the substring part, so i think that's the problem area but i don't know how to fix it.
import java.util.*;
import java.io.*;
public class EZD_readingFiles
{
public static int inputToArray(String fr[], Scanner sf)
{
int max = -1;
while(sf.hasNext())
{
max++;
fr[max] = sf.nextLine();
}
return max;
}
public static void findThe(String fr[], int max)
{
System.out.println("\nHere are the lines that begin with \"The\": \n");
for(int b = 0; b <= max; b++)
{
String s = fr[b].substring(0,4);
if(s.equals("The "))
{
System.out.println(fr[b]);
}
}
}
public static void OutputTheArray(String fr[], int max)
{
System.out.println("Here is the original file: \n");
for(int a = 0; a <= max; a++)
{
System.out.println(fr[a]);
}
}
public static void main(String args[]) throws IOException
{
Scanner sf = new Scanner(new File("EZD_readme.txt"));
String fr[] = new String[5];
int y = EZD_readingFiles.inputToArray(fr,sf);
EZD_readingFiles.OutputTheArray(fr,y);
int z = EZD_readingFiles.inputToArray(fr,sf);
EZD_readingFiles.findThe(fr,z);
sf.close();
}
}
this is my text file with the tester data (EZD_readme.txt):
Every man tries as hard as he can.
The best way is this way.
The schedule is very good.
Cosmo Kramer is a doofus.
The best movie was cancelled.
Try cloning sf and passing it to the other function.
Something like this:
Scanner sf = new Scanner(new File("EZD_readme.txt"));
Scanner sf1 = sf.clone();
int y = EZD_readingFiles.inputToArray(fr,sf);
EZD_readingFiles.OutputTheArray(fr,y);
int z = EZD_readingFiles.inputToArray(fr,sf1);
EZD_readingFiles.findThe(fr,z);
sf.close();
sf1.close();

buffered reader input into char array

I want to take an input from a txt file and put all the characters to the array so I can perform on it some regex functions. But when I try to read the array with a single loop to check it, nothing appears. What is wrong here?
import java.io.BufferedReader;
import java.io.FileReader;
public class Main
{
public static void main(String[] args)
{
try
{
Task2.doTask2();
}catch(Exception e){};
}
}
class Task2
{
public static void doTask2() throws Exception
{
FileReader fr = new FileReader("F:\\Filip\\TextTask2.txt");
BufferedReader br = new BufferedReader(fr);
char[] sentence = null;
int i;
int j = 0;
while((i = br.read()) != -1)
{
sentence[j] = (char)i;
j++;
}
for(int g = 0; g < sentence.length; g++)
{
System.out.print(sentence[g]);
}
br.close();
fr.close();
}
}
You can read a file simply using File.readAllBytes. Then it's not necessary to create separate readers.
String text = new String(
Files.readAllBytes(Paths.get("F:\\Filip\\TextTask2.txt"))
);
In the original snippet, the file reading function is throwing a NullPointerException because sentence was initialized to null and then dereferenced: sentence[j] = (char)i;
The exception was swallowed by the calling function and not printed, which is why you're not seeing it when you run the program: }catch(Exception e){};
Instead of swallowing the exception declare the calling function as throwing the appropriate checked exception. That way you'll see the stack trace when you run it: public static void main(String[] args) throws IOException {
You are using wrong index , use "g" instead of "i" here.:
System.out.println(sentence[g]);
Also, the best and simplest way to do this is:
package io;
import java.nio.file.*;;
public class ReadTextAsString
{
public static String readFileAsString(String fileName)throws Exception
{
return new String(Files.readAllBytes(Paths.get(fileName)));
}
public static void main(String[] args) throws Exception
{
String data = readFileAsString("F:\\Filip\\TextTask2.txt");
System.out.println(data); //or iterate through data if you want to print each character.
}
}

Java: Sending/Receiving int array via socket to/from a program coded in C

I would like to send an entire integer array from Java to another program which is coded in C, and vice versa for receiving.
I have read from here that i should use short array in Java while using normal int array in the C program.
Being new to Java, I'm still not very sure how to do this correctly. Below is my code:
package tcpcomm;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import datatypes.Message;
public class PCClient {
public static final String C_ADDRESS = "192.168.1.1";
public static final int C_PORT = 8888;
private static PCClient _instance;
private Socket _clientSocket;
private ByteArrayOutputStream _toCProgram;
private ByteArrayInputStream _fromCProgram;
private PCClient() {
}
public static PCClient getInstance() {
if (_instance == null) {
_instance = new PCClient();
}
return _instance;
}
public static void main (String[] args) throws UnknownHostException, IOException {
int msg[] = {Message.READ_SENSOR_VALUES};
ByteArrayOutputStream out = new ByteArrayOutputStream();
PCClient pcClient = PCClient.getInstance();
pcClient.setUpConnection(C_ADDRESS, C_PORT);
System.out.println("C program successfully connected");
while (true) {
pcClient.sendMessage(out, msg);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
int[] msgReceived = pcClient.readMessage(in);
}
}
public void setUpConnection (String IPAddress, int portNumber) throws UnknownHostException, IOException{
_clientSocket = new Socket(C_ADDRESS, C_PORT);
_toCProgram = new PrintWriter(_clientSocket.getOutputStream());
_fromCProgram = new Scanner(_clientSocket.getInputStream());
}
public void closeConnection() throws IOException {
if (!_clientSocket.isClosed()) {
_clientSocket.close();
}
}
public void sendMessage(OutputStream out, int[] msg) throws IOException {
int count = 0;
DataOutputStream dataOut = new DataOutputStream(out);
dataOut.writeInt(msg.length);
System.out.println("Message sent: ");
for (int e : msg) {
dataOut.writeInt(e);
System.out.print(e + " ");
if(count % 2 == 1)
System.out.print("\n");
count++;
}
dataOut.flush();
}
public int[] readMessage(InputStream in) throws IOException {
int count = 0;
DataInputStream dataIn = new DataInputStream(in);
int[] msg = new int[dataIn.readInt()];
System.out.println("Message received: ");
for (int i = 0; i < msg.length; ++i) {
msg[i] = dataIn.readInt();
System.out.print(msg[i] + " ");
if(count % 2 == 1)
System.out.print("\n");
count++;
}
return msg;
}
}
Any guidance on how to correct the code appreciated!!
Do i need to change the stream from bytearray to intarray? Sounds like a lot of conversion.. (Based on answers I can find here)
To answer your question: No, you don't need to change streams from byte to int. Part of the nature of I/O streams in Java is that they are byte-based. So when you want to write an int to a stream you need to split it into its byte elements and write them each.
Java uses 4 byte signed integers and you cannot change that. For your counterpart (your C program) you need to make sure that it uses an equivalent type, such as int32_t from stdint.h. This can be considered as part of your "protocol".
Java already provides the means to read and write int, long, etc. values from and to streams with java.io.DataInputStream and java.io.DataOutputStream. It is important to keep in mind that DataOutputStream#writeInt(int) writes the four bytes of an int high to low. This is called Endianness, but I'm pretty sure you know that already. Also this can be considered as another part of your "protocol".
Lastly, when transmitting a structure, the endpoint that's reading must know how much it has to read. For fixed size structures both sides (client and server) know the size already, but arrays can vary. So when sending, you need to tell your counterpart how much you will be sending. In case of arrays it's pretty simple, just send the array length (just another int) first. This can be considered as yet another part of your "protocol".
I've written an example for writing and reading int arrays to and from streams.
package com.acme;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
public class SendAndReceive {
public static void main(String[] args) throws IOException {
int[] ints = new int[] {Integer.MIN_VALUE, -1, 0, 1, Integer.MAX_VALUE};
ByteArrayOutputStream out = new ByteArrayOutputStream();
writeInts(out, ints);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
int[] results = readInts(in);
if (!Arrays.equals(ints, results)) System.out.println("Damn!");
else System.out.println("Aaall's well!");
}
private static void writeInts(OutputStream out, int[] ints) throws IOException {
DataOutputStream dataOut = new DataOutputStream(out);
dataOut.writeInt(ints.length);
for (int e : ints) dataOut.writeInt(e);
dataOut.flush();
}
private static int[] readInts(InputStream in) throws IOException {
DataInputStream dataIn = new DataInputStream(in);
int[] ints = new int[dataIn.readInt()];
for (int i = 0; i < ints.length; ++i) ints[i] = dataIn.readInt();
return ints;
}
}
All you need to do is use the methods writeInts(OutputStream, int[]) and readInts(InputStream) and call them with your socket streams.
I've not implemented a C program for demonstration purposes, because there's no standard socket implementation (although there's the Boost library, but it's not standard and not C but C++).
Have fun!

Finding largest value in an array from a text file

I'm programming in Java. I'm not good at programming, but I'm trying.
I managed to create a file that generates an array of 10k random (in range 1 through 1 million) numbers into a text file. This class is called 'CreateDataFile'
What I'm trying to do now is read the array from the text file created in 'CreateDataFile' from a completely different class. This new class is called 'ProcessDataFile'
The first thing I thought about doing is 'extends' the class. So both classes communicate.
The thing is, I know how to create a for loop in a program and then find the largest number. I just don't understand how to read this text file, and create a for loop that processes from the text file and finds the max value.
Here's my CreateDataFile class
import java.io.*;
import java.util.Random;
public class CreateDataFile {
public static void main(String[] args) {
int [] integers = new int[10000];
Random r = new Random();
try{
PrintWriter p = new PrintWriter("dataset529.txt");
for (int i = 0; i <integers.length; i++) {
int number = r.nextInt(1000000)+1;
p.print(" " + number);
}
p.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Now this generates the numbers I need into a text file called dataset529.
If everything was in one class, I'd just create a for loop.. something like
int max = integers[0];
for(int i = 0; i<integers.length; i++){
if (integers[i] > max)
System.out.println(integers[i]);
}
But as I'm creating my ProcessDataFile class, I'm having a hard time reading the text file created from the CreateDataFile class.
Any ideas on how I can read this text file and run a for loop over it to find the max number like I used above?
Thanks, any help would be appreciated.
First of all, you should write in the file each number on one line so that it's easier when you read the numbers from the file. This can be done just by doing:
p.print(number + "\n");
After that, you can use this code to get the max of all the numbers:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ProcessDataFile {
public static void main(String[] args) throws IOException {
String fileName = "dataset529.txt";
String temp;
int max = Integer.MIN_VALUE;
int i = 0;
int[] numbers = new int[10000];
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
while((temp = br.readLine()) != null) {
if(temp.isEmpty())
break;
numbers[i++] = Integer.parseInt(temp);
}
}
for(i = 0; i < numbers.length; i++)
if(max < numbers[i])
max = numbers[i];
System.out.println(max);
}
Write the content of each number on new line. While reading the file, maintain a max element.
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
public class CreateDataFile {
public static void main(String[] args) {
int[] integers = new int[10000];
Random r = new Random();
try {
PrintWriter p = new PrintWriter("dataset529.txt");
for (int i = 0; i < integers.length; i++) {
int number = r.nextInt(1000000) + 1;
p.print(number + "\n");
}
p.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Now read the file line by line.
public class ProcessDataFile {
public static void main(String[] args) throws IOException {
int max = Integer.MIN_VALUE;
String line = null;
BufferedReader br = new BufferedReader(new FileReader("dataset529.txt"));
while ((line = br.readLine()) != null) {
int num = Integer.parseInt(line);
if (max < num) {
max = num;
}
}
}
System.out.println(max);
}

Categories

Resources