Read txt file into array and create new output.
What I need to do is create a class that creates a text file of an array. (Which I have posted Below)
What I need help with
Once that file is created I need to create a class that reads the numbers that were created and then multiplies all the numbers by the number at position [0][0]. Then creates a new .txt file and puts them in there.
Ex:
Original numbers
5 6 3 4
Output needs to be
25 30 15 20
I have a class that reads the numbers and just prints them out. I cant figure out how to read the numbers and do anything with them.
Code that creates file with array of numbers.....
Code :
import java.io.*;
import java.util.Random;
public class Output
{
public static void main(String args[])
{
final int rowW = 2;
final int colH = 4;
Random rand = new Random();
int [][] array1 = new int [rowW][colH];
for (int row = 0; row < array1.length; row++) {
for (int col = 0; col < array1[row].length; col++) {
array1[row][col] = rand.nextInt(10);
}
}
try{
FileWriter fStream;
PrintWriter myStream;
fStream = new FileWriter( "randomarray.txt");
myStream = new PrintWriter( fStream );
int l= array1.length;
for(int i = 0; i < l; i++) {
for(int j = 0; j <= l; j++) {
myStream.print( " "+ array1[i][j] );
}
}
myStream.flush();
myStream.close();
}
catch (IOException e) {
System.out.println("I/O exception" );
}
}
}
Just reads the array and prints it out. I need it to read the numbers and then be able to multiply them and create a new file with multiplied numbers. (I could just add them to the bottom of the original file if that is possible)
Code :
import java.io.*;
class input {
public static void main(String[] args) {
try {
FileReader fReader;
BufferedReader reader;
int charAsInt;
fReader = new FileReader("randomarray.txt");
reader = new BufferedReader( fReader );
charAsInt = reader.read();
while ( charAsInt != -1 ) {
System.out.print( (char)charAsInt);
charAsInt = reader.read();
}
reader.close();
}
catch (IOException e) {
System.out.println( "I/O exception" );
}
}
}
Thanks in advance for any help
Re: Read txt file into array and create new output.
Quote:
how to read the numbers and do anything with them.
The Scanner class has methods that will read from a text file and convert the String that was read to an int or double value.
The read() method reads bytes from the file and will require you to do some work to convert those bytes back to the number. The Scanner class methods will be much easier to use.