In: Computer Science
/**
* Read integers into array from named file. First element in
* file is a count of number of integers contained in the
file.
*
* @param fileName name of file containing integer
data
*/
void readIntFile(String fileName)
Note: Use the void insert(int value) method defined in the class to add each integer to the array as it is loaded from the file.
Here is a sample code to read data from file
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileReaderSample {
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(System.in);
System.out.println("Please enter file name");
String s = in.nextLine();
Scanner input = new Scanner(new File(s));
int[] arr = new int[100];
int i = 0;
while (input.hasNextInt()) {
int next = input.nextInt();
arr[i] = next;
i++;
}// end while
int nElems = i;
// Print the array contents
System.out.println("Array Contents");
for (i = 0; i < nElems; i++) {
System.out.println(i + "\t" + arr[i]);
}// end for
}// end main
Short Summary:
Implemented the program as per requirement
Attached source code and sample output
**************Please do upvote to appreciate our time. Thank you!******************
Source Code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**This class reads integer data from a file to fill the
array**/
public class HighArray {
/**
* Read integers into array from named file. First
element in
* file is a count of number of integers contained in
the file.
*
* @param fileName name of file containing integer
data
*/
void readIntFile(String fileName)
{
Scanner input =null;
try {
//Create file
with given File name
input = new
Scanner(new File(fileName));
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
int i = 0;
int[] arr = null ;
int arraySize=0;
while (input.hasNextInt())
{
//First element
in the array is size of the array, as it contains no of
elements
if(i==0)
{
arraySize=input.nextInt();
arr = new int[arraySize];
}
else
{
//Load array from second element
int next = input.nextInt();
//Start from zero'th index
arr[i-1] = next;
}
i++;
}// end while
// Print the array contents
System.out.println("*******Array Contents******");
for (i = 0; i < arraySize; i++) {
System.out.println(i + "\t" + arr[i]);
}// end for
input.close();
}// end Method
//Main method to test the above method
public static void main(String[] args)
{
//Create object for HighArray
HighArray obj=new
HighArray();
Scanner in=new
Scanner(System.in);
//Get file name input from
user
System.out.print("Please enter the
file name: ");
obj.readIntFile(in.nextLine());
in.close();
}
}
Code Screenshot:
Output:
InputFile.txt
Output:
**************Please do upvote to appreciate our time.
Thank you!******************