Hello I am writing a program that write and read file XML in Java.
Here is the Writing file
public static void main(String[] args) throws IOException {
File file = new File("C:\\Test\\employee.XML");
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
//int codeEmp = 0;
String nameEmp[] = {"Name A", "Name B", "Name C", "Name D", "Name E"};
String addEmp[] = {"Address A", "Address B",
"Address C", " Address D",
"Address E"};
int saleEmp[] = {2000,1232,7653,1236,3452};
int comEmp[] = {400,100,3000,300,500};
StringBuffer buffer;
StringBuffer buffer1;
for (int i=0;i< nameEmp.length; i++){
randomAccessFile.writeInt(i+1);
buffer = new StringBuffer( nameEmp[i]);
buffer.setLength(10);
randomAccessFile.writeChars(buffer.toString());
buffer1 = new StringBuffer( addEmp[i]);
buffer1.setLength(100);
randomAccessFile.writeChars(buffer1.toString());
randomAccessFile.writeInt(saleEmp[i]);
randomAccessFile.writeInt(comEmp[i]);
}
randomAccessFile.close();
}
The Reader is
public static void main(String[] args) throws IOException {
File file = new File("C:\\Test\\employee.XML");
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
int codeEmp, position = 0;
char nameEmp[] = new char[10];
char addEmp[] = new char [100];
int saleEmp , comEmp;
for(;;){
randomAccessFile.seek(position);
codeEmp = randomAccessFile.readInt();
for (int i = 0; i < nameEmp.length; i++) {
nameEmp[i] = randomAccessFile.readChar();
}
String nameEmpS= new String(nameEmp);
for (int i = 0; i < addEmp.length; i++) {
addEmp[i] = randomAccessFile.readChar();
}
String addEmpS= new String(addEmp);
saleEmp =randomAccessFile.readInt();
comEmp=randomAccessFile.readInt();
System.out.println("Cod Emp: " + codeEmp + ", nombre: " +nameEmpS+ ", dirección: "+addEmpS+
", sale: " + saleEmp+ ", comisión: " + comEmp );
position= position + 36;
if (randomAccessFile.getFilePointer()==file.length())break;
}
randomAccessFile.close();
}
The problem is that when I run the reader file, it's return many lines and only the first line is okay but the rest are wrong. How can I fix it?
Here is the console
Cod Emp: 1, nombre: Name A , dirección: Address A , sale: 2000, comisión: 400
Cod Emp: 7536672, nombre: A , dirección: Name B Ad, sale: 6553714, comisión: 6619251
Cod Emp: 0, nombre: , dirección: Ɛ Name B Address B , sale: 0, comisión: 0
You are assigning a "random" next read position here:
position= position + 36;
That makes no sense unless there is 36 bytes padding after every record. Comment out the line position= position + 36; and randomAccessFile.seek(position); because if you have the matched up each write with a read then the next seek position is moved correctly.
Also note:
writing a file called employee.XML which isn't XML format is very misleading for others.
You don't need to use RandomAccessFile here as all your writes are sequential.
Related
I have created a simple program that sorts integers in an input file using different algorithms. I also use filewriter to output results to another file. Unfortunately no matter how I change my code, file gets overridden. Any advice?
Been searching for answer on google and tried changing the way I input the syntax but nothing works.
important bits:
setting the writer up
try {
FileWriter fileWriter = new FileWriter ("Sorted output.txt");
//BufferedWriter bufferedWriter = new BufferedWriter (fileWriter);
PrintWriter out = new PrintWriter (new FileWriter("Sorted output.txt", true));
outputting to the file
out.println("User's own data set sorted using bubble sort.");
out.println(unsortedArray + Arrays.deepToString(FileOne));
out.println("Sorted Array looks like this:" + Arrays.toString(intArrayBubble));
out.println(timeToSort + bubbleSortIs + bubbleTime + "ms");
it works fine, however its used in a do while loop, with nested if statements, and each one overrides the other.
Rest of code in case its required - UPDATED - still not working
import java.io.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class PDD_Sorting {
public static void main (String [] pArgs)
{
//Array for a file
String[] FileOne;
FileOne = new String[0];
int optionOne = 1,
optionTwo = 2,
optionThree = 3,
secondaryOptionOne = 1,
secondaryOptionTwo = 2,
secondaryOptionThree = 3,
userSelection,
subUserSelection;
String unsortedArray = "Unsorted array is: ",
bubbleSort = "Sorted array using bubble sort: ",
selectionSort = "Sorted array using selection sort: ",
insertionSort = "Sorted array using insertion sort: ",
timeToSort = "Time needed to sort this array using ",
bubbleSortIs = "bubble sort is ",
selectionSortIs = "selection sort is ",
insertionSortIs = "insertion sort is ",
welcomeToSorter = "Welcome to the SORTER - program that can sort your txt files containing integeres in an ascending order!",
notFiles = "Integers, not files :)",
pleaseSelect = "Please select one of the following options, by enetering a number asociated with it.",
optionOneUserInput = "1. Sort your own data set - input your own set of data (integers, separated by colons, no spaces) into the Input file.",
optionTwoPredefined = "2. Use predetermind set of data to test the algorythms.",
optionThreeExit = "3. Exit the program.",
subMenuPleaseSelect = "Please select which algorythm would you like to use to sort this file.",
optionBubble = "(1) - Bubble Sort.",
optionSelection = "(2) - Selection Sort.",
optionInsertion = "(3) - Insertion Sort.",
usersDataBubble = "User's own data set sorted using bubble sort.",
sortedArrayLooks = "Sorted Array looks like this:",
msTime = "ms",
usersDataSelection = "User's own data set sorted using selection sort.",
usersDataInsertion = "User's own data set sorted using insertion sort.",
validOption = "Please enter a valid option i.e. 1,2 or 3",
lessThanZero = "If time shown in ms is 0, that means the time needed to conduct the sort is shorter than 1ms.",
fileCreated = "File created.",
terminatingProgram = "Terminating the program.",
unableToWriteFile = "Unable to write to file";
System.out.println(welcomeToSorter);
System.out.println(notFiles);
Scanner tInput = new Scanner (System.in);
try {
FileWriter fileWriter = new FileWriter ("Sorted output.txt");
//BufferedWriter bufferedWriter = new BufferedWriter (fileWriter);
PrintWriter out = new PrintWriter (new FileWriter("Sorted output.txt", true));
do {
System.out.println(pleaseSelect);
System.out.println(optionOneUserInput);
System.out.println(optionTwoPredefined);
System.out.println(optionThreeExit);
// Scanner tInput = new Scanner (System.in);
userSelection = tInput.nextInt();
if (userSelection == optionOne) {
//System.out.println("Please enter a valid path for your file.");
String[] splitFile = null;
//String userFile = tInput.next();
FileOne = getAndPrepareFile(splitFile);
System.out.println(subMenuPleaseSelect);
System.out.println(optionBubble);
System.out.println(optionSelection);
System.out.println(optionInsertion);
subUserSelection = tInput.nextInt();
if (subUserSelection == secondaryOptionOne) {
int size = FileOne.length;
int [] intArrayBubble = new int [size];
for(int i=0; i<size; i++) {
intArrayBubble[i] = Integer.parseInt(FileOne[i]);
}
bubbleSort(intArrayBubble);
long bubbleTime = timeCount(intArrayBubble);
out.println(usersDataBubble);
out.println(unsortedArray + Arrays.deepToString(FileOne));
out.println(sortedArrayLooks + Arrays.toString(intArrayBubble));
out.println(timeToSort + bubbleSortIs + bubbleTime + msTime);
}
else if (subUserSelection == secondaryOptionTwo) {
int size2 = FileOne.length;
int [] intArraySelection = new int [size2];
for(int i=0; i<size2; i++) {
intArraySelection[i] = Integer.parseInt(FileOne[i]);
}
doSelectionSort(intArraySelection);
long selectionTime = timeCount(intArraySelection);
out.println(usersDataSelection);
out.println(unsortedArray + Arrays.deepToString(FileOne));
out.println(sortedArrayLooks + Arrays.toString(intArraySelection));
out.println(timeToSort + selectionSortIs + selectionTime + msTime);
}
else if (subUserSelection == secondaryOptionThree) {
int size3 = FileOne.length;
int [] intArrayInsertion = new int [size3];
for(int i=0; i<size3; i++) {
intArrayInsertion[i] = Integer.parseInt(FileOne[i]);
}
doInsertionSort(intArrayInsertion);
long insertionTime = timeCount(intArrayInsertion);
out.println(usersDataInsertion);
out.println(unsortedArray + Arrays.deepToString(FileOne));
out.println(sortedArrayLooks + Arrays.toString(intArrayInsertion));
out.println(timeToSort + insertionSortIs + insertionTime + msTime);
}
else {
System.out.println(validOption);
tInput.next();
}
}
else if (userSelection == optionTwo){
//file being prepared and loaded via function
String[] splitFilePredefined = null;
FileOne = getAndPrepareFilePredefined(splitFilePredefined);
//converting string array into int array so the method can sort it.
int size = FileOne.length;
int [] intArrayBubble = new int [size];
for(int i=0; i<size; i++) {
intArrayBubble[i] = Integer.parseInt(FileOne[i]);
}
int size2 = FileOne.length;
int [] intArraySelection = new int [size2];
for(int i=0; i<size2; i++) {
intArraySelection[i] = Integer.parseInt(FileOne[i]);
}
int size3 = FileOne.length;
int [] intArrayInsertion = new int [size3];
for(int i=0; i<size3; i++) {
intArrayInsertion[i] = Integer.parseInt(FileOne[i]);
}
//inserting pre-prepared int arrays into variables including a timecount method
int bubbleTime = timeCount(intArrayBubble);
int selectionTime = timeCount(intArraySelection);
int insertionTime = timeCount(intArrayInsertion);
//sorting array using various sorts
bubbleSort(intArrayBubble);
doSelectionSort(intArraySelection);
doInsertionSort(intArrayInsertion);
//out.println("Sorted arrray using insertion sort looks like this: " + Arrays.toString(intArrayInsertion));
out.println(timeToSort + bubbleSortIs + bubbleTime + "ms");
out.println(timeToSort + selectionSortIs + selectionTime + "ms");
out.println(timeToSort + insertionSortIs + insertionTime + "ms");
out.println(lessThanZero);
System.out.println(fileCreated);
}
else if (userSelection == optionThree){
System.out.println(terminatingProgram);
System.exit(0);
}
else {
System.out.println(validOption);
tInput.next();
}
out.flush();
out.close();
//tInput.close();
}while (userSelection != optionThree);
}
catch (Exception e)
{
System.out.println(unableToWriteFile);
tInput.next();
}
tInput.close();
}//end main
//method that fetches the file from predefined, hardcoded location and removes comas, esentially prepares the file for the next phase
private static String[] getAndPrepareFile (String[] splitFile)
{
Scanner fileIn = null;
try
{
fileIn = new Scanner(new FileInputStream("C:\\Users\\Greg\\Documents\\Programming\\PDD - Assignment 1\\Input.txt"));
String fileNew = fileIn.next();
splitFile = fileNew.split(",");
//System.err.println(Arrays.toString(splitFile)); //Arrays.toString needed to print the array correctly, otherwise it prints the address of the object
fileIn.close();
}
catch (IOException e)
{
System.out.println("File not found.");
//System.exit(0);
}
return splitFile;
}
//as above but works for predefined file, that can be generated using randomNumber.java program
private static String[] getAndPrepareFilePredefined (String[] splitFilePredefined)
{
Scanner fileIn = null;
try
{
fileIn = new Scanner(new FileInputStream("C:\\Users\\Greg\\Documents\\Programming\\PDD - Assignment 1\\Generated input.txt"));
String fileNew = fileIn.next();
splitFilePredefined = fileNew.split(",");
//System.err.println(Arrays.toString(splitFile)); //Arrays.toString needed to print the array correctly, otherwise it prints the address of the object
fileIn.close();
}
catch (IOException e)
{
System.out.println("File not found.");
//System.exit(0);
}
return splitFilePredefined;
}
//method used to sort a file using bubble sort
private static void bubbleSort(int[] arr) {
int n = arr.length;
int temp = 0;
for(int i=0; i < n; i++){
for(int j=1; j < (n-i); j++){
if(arr[j-1] > arr[j]){
//swap elements
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
}
}
//method used to sort a file using selection sort
private static int[] doSelectionSort(int[] arr){
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++)
if (arr[j] < arr[index])
index = j;
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
return arr;
}
//method used to sort a file using sinsertion sort
private static int[] doInsertionSort(int[] input){
int temp;
for (int i = 1; i < input.length; i++) {
for(int j = i ; j > 0 ; j--){
if(input[j] < input[j-1]){
temp = input[j];
input[j] = input[j-1];
input[j-1] = temp;
}
}
}
return input;
}
//method used to calculate how much time has lapsed while using any of the given sort methods, outputs in ms, if less than 1 ms, outputs 0ms
private static int timeCount (int[] anArray)
{
long start = System.nanoTime();
Arrays.sort(anArray);
long end = System.nanoTime();
long timeInMillis = TimeUnit.MILLISECONDS.convert(end - start, TimeUnit.NANOSECONDS);
//System.out.println("Time spend in ms: " + timeInMillis);
return (int) timeInMillis;
}
}//end class
File gets constantly overridden, how do i stop this and make it add to file instead?
You don't need the first FileWriter fileWriter = new FileWriter("Sorted output.txt");; this is actually creating/overwriting the file, after which your PrintWriter opens it again for appending.
So, just change
// ... omitting beginning
try {
FileWriter fileWriter = new FileWriter ("Sorted output.txt");
//BufferedWriter bufferedWriter = new BufferedWriter (fileWriter);
PrintWriter out = new PrintWriter (new FileWriter("Sorted output.txt", true));
do {
// ... omitting rest
to
// ... omitting beginning
try {
//BufferedWriter bufferedWriter = new BufferedWriter (fileWriter);
PrintWriter out = new PrintWriter (new FileWriter("Sorted output.txt", true));
do {
// ... omitting rest
Move out.close() outside the loop
else {
System.out.println("Please enter a valid option i.e. 1,2 or 3");
tInput.next();
}
out.flush();
/* THIS -> out.close(); <- THIS */
//tInput.close();
}while (userSelection != optionThree);
out.close();
}
I tried your code and your problem is not that the file is being overwritten, but that you are closing the outputstream in the first iteration.
I am trying to write to a file (leaders.txt) and I am having an issue with the way the data I have calculated is showing in the file.
import java.io.*;
import java.util.*;
public class readStats {
public static int getStat(String letter, String stats) {
int count = stats.length() - stats.replace(letter, "").length();
return count;
}
public static void main(String[] args) throws FileNotFoundException {
String hitsLeader = null;
String walksLeader = null;
String hitsByPitchLeader = null;
String strikeoutsLeader = null;
String battingAverageLeader = null;
int maxHits = 0;
int maxWalks = 0;
int maxHitsByPitch = 0;
int maxStrikeouts = 0;
int maxBa = 0;
java.io.File file = new java.io.File("stats.txt");
Scanner input = new Scanner(file);
//Find out number for each category
while (input.hasNextLine()) {
String line = input.nextLine();
String[] parts = line.split(" ");
int hits = getStat("H", parts[1]);
int outs = getStat("O", parts[1]);
int walks = getStat("W", parts[1]);
int hitsByPitch = getStat("P", parts[1]);
int strikeouts = getStat("K", parts[1]);
int sacrifices = getStat("S", parts[1]);
int totalAtBats = hits + outs + strikeouts;
double ba = ((double)hits/(double)totalAtBats );
//System.out.println("Player " + parts[0]);
if (hits > maxHits) {
maxHits = hits;
hitsLeader = parts[0];
}
if (walks > maxWalks) {
maxWalks = walks;
walksLeader = parts[0];
}
if (hitsByPitch > maxHitsByPitch) {
maxHitsByPitch = hitsByPitch;
hitsByPitchLeader = parts[0];
}
if (strikeouts > maxStrikeouts) {
maxHits = hits;
strikeoutsLeader = parts[0];
}
if (ba > maxBa) {
maxHits = hits;
battingAverageLeader = parts[0];
}
//Create PrintWriter
java.io.PrintWriter output = new java.io.PrintWriter("leaders.txt");
// Print LEAGUE LEADERS to leaders.txt
output.println(parts[0]);
output.printf("BA: %.3f", ba);
output.println("H: " + hits);
output.println("BB: " + walks);
output.println("K: " + strikeouts);
output.println("HBP: " + hitsByPitch);
output.println("");
output.println("LEAGUE LEADERS");
output.println("BA: " + battingAverageLeader);
output.println("H: " + hitsLeader);
output.println("BB: " + walksLeader);
output.println("K: " + strikeoutsLeader);
output.println("HPB: " + hitsByPitchLeader);
output.close();
}
}
}
Output in leaders.txt
Pudge
BA: 0.450H: 9
BB: 2
K: 8
HBP: 1
LEAGUE LEADERS
BA: Pudge
H: Piazza
BB: Griffey
K: Pudge
HPB: Griffey
Stats.txt
Griffey HHOHOKWOHKSPOOWSHHWWWWWWW
Piazza OOHHHKPSOHOOHWWHOSSSHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
Pudge HHHHKOOHHHSWWHHOPKKKKKKK
Desired Output
Griffey
BA: 0.462
H: 6
BB: 9
K: 2
HBP: 1
Piazza
BA: 0.833
H: 35
BB: 2
K: 1
HBP: 1
Pudge
BA: 0.450
H: 9
BB: 2
K: 8
HBP: 1
I need the output to display all three of the players that are associated in the file stats.txt, not just one.
Start the printer before the while loop and close it afterwards.
The league leaders should be printed only once.
Move those after the loop when you have the numbers of each player compared.
java.io.PrintWriter output = new java.io.PrintWriter("leaders.txt");
while (input.hasNextLine()) {
...
}
output.println("LEAGUE LEADERS");
output.println("BA: " + battingAverageLeader);
output.println("H: " + hitsLeader);
output.println("BB: " + walksLeader);
output.println("K: " + strikeoutsLeader);
output.println("HPB: " + hitsByPitchLeader);
output.close();
Edit: Add
output.println();
after
output.printf("BA: %.3f", ba);
printf doesn't start a new line.
I'm trying use the class RandomAccessFile, but I have a problem with the Strings.
This is the first part. Write in a File:
public static void main(String[] args) throws IOException {
File file = new File("/home/pep/java/randomFile.dat");
RandomAccessFile fitxerAleatori = new RandomAccessFile(file, "rw");
String[] surnames = { "SMITH",
"LOMU" };
int[] dep = { 10,
20 };
Double[] salary = { 1200.50,
1200.50 };
StringBuilder buffer = null;
int n = surnames.length;
for (int i = 0; i<n; i++){
randomFile.writeInt(i+1); //ID
buffer = new StringBuilder(surnames[i]);
buffer.setLength(10); //10 characters
randomFile.writeChars(buffer.toString());
randomFile.writeInt(dep[i]);
randomFile.writeDouble(salary[i]);
}
randomFile.close();
}
In the second part, I try read this file:
File file = new File("/home/pep/java/randomFile.dat");
RandomAccessFile randomFile = new RandomAccessFile(file, "r");
char[] surname = new char[10];
char aux;
int id, dep, pos;
Double salary;
pos = 0;
for (;;) {
randomFile.seek(pos);
id = randomFile.readInt();
for (int i = 0; i < surname.length; i++) {
aux = randomFile.readChar();
surname[i] = aux;
}
String surnameStr = new String(surname); //HERE IS THE PROBLEM!!
dep = randomFile.readInt();
salary = randomFile.readDouble();
System.out.println("ID: " + id + ", Surname: " + surnameStr + ", Departament: " + dep + ", Salary: " + salary);
pos = pos + 36; // 4 + 20 + 4 + 8
if (randomFile.getFilePointer() == randomFile.length())
break;
}
randomFile.close();
}
Well, when I hope read:
ID: 1, Surname: SMITH, Dep: 10, Salary: 1200.50
I recived:
ID: 1, Surname: SMITH
It's like in the surname there is a end of line, because if I don't display the surname, the other info is correct.
Thank you!
Where does cognom come from? [Edit: OK, I found it. It's Catalan for surname. And now the typo coming from departamento is also clear. :-]
What do you get if you insert System.out.println( Arrays.toString( surname )) before the problem line? I assume it's something like [S, M, I, T, H, [], [], [], [], []] (in Eclipse's Console view). Where [] stands for a square, i.e. a non-printable character.
What do you get if you insert System.out.println( (int) surname[5] )? I assume it's 0. And I assume this 0 value is causing the problem.
What do you get if you use a surname that's exactly 10 characters long?
Hint 1: There's a typo in Departament.
Hint 2: Give System.out.printf(...) a chance in favour of println(...).
Hint 3: The if in your solution can be shortened to the more elegant:
cognom[i] = aux != 0 ? aux : ' ';
The problem was in the char array. I change de loop for that read the chars:
for (int i = 0; i < surname.length; i++) {
aux = randomFile.readChar();
surname[i] = aux != 0 ? aux : ' ';
}
Creating a StringBuffer and setting its length to ten will cause nulls to be written for strings shorter than ten characters, and that in turn will cause a decoding problem when you read. It would be much better to create a String, pad it with spaces to ten chars, write it, then trim() the resulting String when you read it.
I have this method where i am trying to read in from a text file and then add whats in it to my array ,my method seems to be okay , but when i rum my program i am getting null on the screen
please help here is my code.
File text = new File("C:\\Users\\Stephen\\Desktop\\CA2\\src\\Management_System_Package\\GAMES.txt");
Scanner scnr = new Scanner(text);
String GameLine;
GameLine = scnr.nextLine();
while (scnr.hasNextLine()) {
Management_System Game = new Management_System("", "", 0, 0, 0);
int Comma1 = GameLine.indexOf(", ");
String Title = GameLine.substring(0, Comma1).trim();
Game.setTitle(Title);
System.out.print(Title);
int Comma2 = GameLine.indexOf(", ", Comma1 + 1 );
String Genre = GameLine.substring(Comma1 + 1, Comma2);
Game.setGenre(Genre);
int Comma3 = GameLine.indexOf(", ", Comma2 + 1 );
String ID = GameLine.substring(Comma2 + 1, Comma3);
Game.setID(Double.parseDouble(ID));
int Comma4 = GameLine.indexOf(", ", Comma3 + 1 );
String Rating = GameLine.substring(Comma3 + 1, Comma4);
Game.setRating(Integer.parseInt(Rating));
String Quantity = GameLine.substring(Comma4 + 1).trim();
Game.setQuantity(Integer.parseInt(Quantity));
add(Game);
GameLine = in.nextLine();
It is because your code has a bug that you read a line out of the loop and you will always skip the last line of your file. If your file has only one line, scnr.hasNextLine() will be false and the while loop will not be run into.
And I think split() is a better way to get the strings and integers you want. Code like this:
String GameLine;
while (scnr.hasNextLine()) {
GameLine = scnr.nextLine();
Management_System Game = new Management_System("", "", 0, 0, 0);
String[] tags = GameLine.split(",");
Game.setTitle(tags[0]);
Game.setGenre(tags[1]);
Game.setID(Double.parseDouble(tags[2]));
Game.setRating(Integer.parseInt(tags[3]));
Game.setQuantity(Integer.parseInt(tags[4]));
add(Game);
}
So I have a text file with items like look like this:
350279 1 11:54 107.15
350280 3 11:55 81.27
350281 2 11:57 82.11
350282 0 11:58 92.43
350283 3 11:59 86.11
I'm trying to create arrays from those values, in which the first values of each line are in an array, the second values of each line are in an array, and so on.
This is all the code I have right now, and I can't seem to figure out how to do it.
package sales;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Sales {
public static void main (String[] args) throws FileNotFoundException {
Scanner reader = new Scanner(new File("sales.txt"));
int[] transID = new int[reader.nextInt()];
int[] transCode = new int[reader.nextInt()];
String[] time = new String[reader.next()];
double[] trasAmount = new double[reader.hasNextDouble()];
}
}
It's difficult to build an array this way, because Arrays have fixed size... you need to know how many elements they have. If you use a List instead, you don't have to worry about knowing the number of elements in advance. Try this (note: there is no error checking here!):
public static void main (String[] args) throws FileNotFoundException {
Scanner reader = new Scanner(new File("sales.txt"));
List<Integer> ids = new LinkedList<>();
List<Integer> codes = new LinkedList<>();
List<String> times = new LinkedList<>();
List<Double> amounts = new LinkedList<>();
// Load elements into Lists. Note: you can just use the lists if you want
while(reader.hasNext()) {
ids.add(reader.nextInt());
codes.add(reader.nextInt());
times.add(reader.next());
amounts.add(reader.nextDouble());
}
// Create arrays
int[] idArray = new int[ids.size()];
int[] codesArray = new int[codes.size()];
String[] timesArray = new String[times.size()];
double[] amountsArray = new double[amounts.size()];
// Load elements into arrays
int index = 0;
for(Integer i : ids) {
idArray[index++] = i;
}
index = 0;
for(Integer i : codes) {
codesArray[index++] = i;
}
index = 0;
for(String i : times) {
timesArray[index++] = i;
}
index = 0;
for(Double i : ids) {
amountsArray[index++] = i;
}
}
Use Array list because Arrays have fixed size and using Arraylist you add the elements dynamically
Scanner reader = new Scanner(new File("test.txt"));
List<Integer> transID = new ArrayList<Integer>();
List<Integer> transCode = new ArrayList<Integer>();
List<String> time= new ArrayList<String>();
List<Double> trasAmount = new ArrayList<Double>();
while(reader.hasNext() )
{
transID.add(reader.nextInt());
transCode.add(reader.nextInt());
time.add(reader.next());
trasAmount.add(reader.nextDouble());
}
System.out.println(transID.toString());
System.out.println(transCode.toString());
System.out.println(time.toString());
System.out.println(trasAmount.toString());
Output of the above code
transID [350279, 350280, 350281, 350282, 350283]
transCode [1, 3, 2, 0, 3]
time [11:54, 11:55, 11:57, 11:58, 11:59]
trasAmount [107.15, 81.27, 82.11, 92.43, 86.11]
You'll need a while loop to check for input. Since not all inputs are integers you might do something like:
while(reader.hasNextLine()){ //checks to make sure there's still a line to be read in the file
String line=reader.nextLine(); //record that next line
String[] values=line.split(" "); //split on spaces
if(values.length==4){
int val1=Integer.parseInt(values[0]); //parse values
int val2=Integer.parseInt(values[1]);
String val3=values[2];
double val4=Double.parseDouble(values[3]);
//add these values to your arrays. Might have to "count" the number of lines on a first pass and then run through a second time... I've been using the collections framework for too long to remember exactly how to work with arrays in java when you don't know the size right off the bat.
}
}
In addition to my comment here are 3 ways how you cant do it
read into single arrays
int size = 2;
// first allocate some memory for each of your arrays
int[] transID = new int[size];
int[] transCode = new int[size];
String[] time = new String[size];
double[] trasAmount = new double[size];
Scanner reader = new Scanner(new File("sales.txt"));
// keep track of how many elements you have read
int i = 0;
// start reading and continue untill there is no more left to read
while(reader.hasNext()) {
// since array size is fixed and you don't know how many line your file will have
// you have to reallocate your arrays when they have reached their maximum capacity
if(i == size) {
// increase capacity by 5
size += 5;
// reallocate temp arrays
int[] tmp1 = new int[size];
int[] tmp2 = new int[size];
String[] tmp3 = new String[size];
double[] tmp4 = new double[size];
// copy content to new allocated memory
System.arraycopy(transID, 0, tmp1, 0, transID.length);
System.arraycopy(transCode, 0, tmp2, 0, transCode.length);
System.arraycopy(time, 0, tmp3, 0, time.length);
System.arraycopy(trasAmount, 0, tmp4, 0, trasAmount.length);
// reference to the new memory by your old old arrays
transID = tmp1;
transCode = tmp2;
time = tmp3;
trasAmount = tmp4;
}
// read
transID[i] = Integer.parseInt(reader.next());
transCode[i] = Integer.parseInt(reader.next());
time[i] = reader.next();
trasAmount[i] = Double.parseDouble(reader.next());
// increment for next line
i++;
}
reader.close();
for(int j = 0; j < i; j++) {
System.out.println("" + j + ": " + transIDList.get(j) + ", " + transCodeList.get(j) + ", " + timeList.get(j) + ", " + trasAmountList.get(j));
}
as you see this is a lot of code.
Better you use lists so get rid of the overhead of reallocation and copying (at leas in your own code)
read into single lists
// instanciate your lists
List<Integer> transIDList = new ArrayList<>();
List<Integer> transCodeList = new ArrayList<>();
List<String> timeList = new ArrayList<>();
List<Double> trasAmountList = new ArrayList<>();
reader = new Scanner(new File("sales.txt"));
int i = 0;
while(reader.hasNext()) {
// read
transIDList.add(Integer.parseInt(reader.next()));
transCodeList.add(Integer.parseInt(reader.next()));
timeList.add(reader.next());
trasAmountList.add(Double.parseDouble(reader.next()));
i++;
}
reader.close();
for(int j = 0; j < i; j++) {
System.out.println("" + j + ": " + transIDList.get(j) + ", " + transCodeList.get(j) + ", " + timeList.get(j) + ", " + trasAmountList.get(j));
}
You see here how small the code went? But but it still can get better...
A line in the sales.txt file seem to constitute data elements of some entity, why not put them in an object ? for that you may write a class named Trans, some think like this:
class Trans {
public int transID;
public int transCode;
public String time;
public double trasAmount;
#Override
public String toString() {
return transID + ", " + transCode + ", " + time + ", " + trasAmount;
}
}
Then you can use this class to hold the data you read from your file and put each object of that class in a list.
reading into a list of objects
reader = new Scanner(new File("sales.txt"));
List<Trans> transList = new ArrayList<>();
int i = 0;
while(reader.hasNext()) {
Trans trans = new Trans();
trans.transID = Integer.parseInt(reader.next());
trans.transCode = Integer.parseInt(reader.next());
trans.time = reader.next();
trans.trasAmount = Double.parseDouble(reader.next());
transList.add(trans);
i++;
}
reader.close();
for(Trans trans : transList) {
System.out.println("" + i++ + ": " + trans);
}
Output of all 3 methods
0: 350279, 1, 11:54, 107.15
1: 350280, 3, 11:55, 81.27
2: 350281, 2, 11:57, 82.11
3: 350282, 0, 11:58, 92.43
4: 350283, 3, 11:59, 86.11
Here is a sample code to read the values from the file and write into an array. Sample code has logic for int array, you can replicate it for other array types as well.
package sales;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class Sales {
public static void main (String[] args) throws IOException {
FileInputStream fstream = new FileInputStream("sales.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = br.readLine()) != null) {
String[] tokens = strLine.split(" ");
int[] transID = convertStringToIntArray(tokens[0]);
for(int i = 0 ; i < transID.length ; i++ )
System.out.print(transID[i]);
}
}
/** function to convert a string to integer array
* #param str
* #return
*/
private static int[] convertStringToIntArray(String str) {
int intArray[] = new int[str.length()];
for (int i = 0; i < str.length(); i++) {
intArray[i] = Character.digit(str.charAt(i), 10);
}
return intArray;
}
}