Importing a .dat File Java - java

I've searched the internet for roughly an hour and a half now, and I can't for the life of me figure out where I've gone wrong.. Help!!
My problem is that every time I try and run it I don't receive an error until it searches for the file and without fail, it replies "File not found." I'm on a MAC I think I'm typing the directory in properly but something is messed up..
(When opening numEven.dat)
For my input I've tried "numEven.dat" (placing the dat file in the same directory as the java file)
I've also tried "/Users/java/numEven.dat" and "Users/java/numEven.dat"
I know it is in that directory. What am I doing wrong?
Main Class file:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class StatDriver
{
public static void main(String[] args)
{
String fileName = "";
Scanner scan = new Scanner(System.in);
double[] array = new double[20];
System.out.print(" Enter file name: ");
fileName = scan.next();
System.out.println("\n \n \n \n My Grades - View Statistics");
System.out.println(" ------------------------");
// int valueCount = readFile(array,fileName);
array = readFile(array, fileName);
Stat stat = new Stat(array, array.length);
// call each calc on Stat class and display results for each method
stat.calcAvg();
stat.calcMedian();
stat.findMax();
stat.findMin();
// print the return values for each of the above out to the user
}
public static double[] readFile(double[] array, String fileName)
{
int valueCount = 0;
FileIO importFile = new FileIO ();
importFile.main(array, fileName);
System.out.println(array);
valueCount = array.length;
// return valueCount;
return array;
}
}
FileIO class:
import java.util.Scanner;
import java.io.*;
public class FileIO
{
public void main (double[] array, String fileName)
{
double [] num = new double[5];
Scanner inFile;
int i = 0;
try
{
System.out.println(fileName);
inFile = new Scanner(new File("fileName"));
while(inFile.hasNextDouble())
{
array[i] = inFile.nextDouble();
i++;
}
inFile.close();
for(int x = 0; x < i; x++)
System.out.println(" " + num[x]);
}
catch(FileNotFoundException e)
{
System.out.println (" File not found");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println (" array index too large");
}
}
}

Try by changing
inFile = new Scanner(new File("fileName"));
with
inFile = new Scanner(new File(fileName));
in the method FileIO.main
Other than that (having no link to the problem), you could make the method FileIO.main static, and take advantage of Java collections to avoid hardcoding the number of elements of the double you want to read from the file. In the same method you are declaring a variable double[] num but not using it at all.

Related

I keep getting the java.util.NoSuchElementException but I do not see where the error lies

I am trying to write a java program that reads a text file and counts the number of times each word occurs. But I keep getting the No such element Exception. I assume there is something wrong with the ArrayList or how I am accessing the elements of it. Any help would be appreciated.
package text_analyzer;
import java.io.File;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
public class Text_analyzer
{
public static void main(String[] args) throws Exception
{
File file = new File("TestFile.txt");
Scanner sc = new Scanner(file);
int i = 0, indexOfWord = 0, count = 0;
List<String> words = new ArrayList<String>();
List<Integer> wordCount = new ArrayList<Integer>();
while (sc.hasNextLine())
{
String word = sc.next();
if(words.contains(word))
{
indexOfWord = words.indexOf(word);
count = wordCount.get(indexOfWord);
count = count+1;
wordCount.add(indexOfWord, count);
}
else
{
words.add(i,word);
wordCount.add(i,1);
i++;
}
}
sc.close();
int no_of_elements = words.size();
for(int j = 0; j < no_of_elements; j++)
System.out.println(words.get(j));
}
}
Your logic is correct;
Check the path of the file, and make sure it is present or add an additional check in code.
File Path
Add exception handling for new File() method in case file is not found.
File file = new File("C:\\work\\TestFile.txt");
Scanner sc = null;
try {
sc = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Result: Output result

When I store my big text file into arraylist the size is only 4?

import java.awt.Graphics;
import java.awt.List;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundEsxception;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class Benford {
static Object i = null;
static ArrayList<String> list = new ArrayList<String>();
private static String data;
public static void BenfordPercents() {
int one = 0;
int two = 0;
int three = 0;
int four = 0;
int five = 0;
int six = 0;
int seven = 0;
int eight = 0;
int nine = 0;
return;
}
public static void main(String[] args) throws IOException {
DrawingPanel g = new DrawingPanel(500, 500);
Graphics brush = g.getGraphics();
String popData = null;
readCount(popData);
BenfordPercents();
}
public static void readCount(String popdata) throws IOException {
System.out.println("Please make sure the data file is name popData.txt");
System.out.println("We are loading popData.txt...");
Scanner console = new Scanner(System.in);
// Scanner console = new Scanner((new File("popData.txt")));
try {
i = new FileInputStream("popData.txt");
} catch (FileNotFoundException e) {
System.out.println("We cannot locate popData.txt");
System.out.println("Please make sure popData.txt is in the same location" + " as your code file!");
return;
}
System.out.println("popData.txt has loaded!");
System.out.println("");
System.out.println("Please press enter to show data!");
data = console.nextLine();
File file = new File(popdata + ".txt");
FileInputStream fis = new FileInputStream("popdata.txt");
byte[] flush = new byte[1024];
int length = 0;
while ((length = fis.read(flush)) != -1) {
list.add(new String(flush));
// System.out.println(new String(flush));
// System.out.println(list.toString());
}
// Scanner x = new Scanner((new File("popData.txt")));
// while(x.hasNext()){
// list.add(x.next());
// }
fis.close();
}
}
I have a text document with all the numbers of populiation from this link here:
https://en.wikipedia.org/wiki/List_of_countries_and_dependencies_by_population
The text document looks like this:
China 1369480000
India 1270250000
United 320865000
Indonesia 255461700
Brazil 204215000
Pakistan 189607000
..etc
..etc
the list is pretty long.
and when I try to store all of these numbers into an array list and I try to print the array list size it just returns 4?
If you want a list-entry for each line, you should prefer a BufferedReader.
FileInputStream fis = new FileInputStream("popdata.txt")
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
while((String line = br.readLine()) !=null) {
list.add(line);
}
The size of 4 is only the size of your arraylist - each element of your array list was build from an byte-array with a length of 1024. This means that your list either contains about 3K until 4K of data.

Getting file input from two source files

I am trying to write a program that merges two arrays from numbers that are in two different text files into a third array.
I have the method done to merge the two arrays into the third array.
But I don't know how to get the numbers from the second file.
Here is my current code :
public static void main(String[] args) {
int[] mergedArray = {};
Scanner input = new Scanner(System.in);
System.out.println("Enter the name of your first file (including file extension): ");
String filename = input.next();
int[] firstArray;
try (Scanner in = new Scanner(new File(filename)))
{
int count = in.nextInt();
firstArray = new int[count];
firstArray[0] = count;
for (int i = 0; in.hasNextInt() && count != -1 && i < count; i++) {
firstArray[i] = in.nextInt();
}
} catch (final FileNotFoundException e) {
System.out.println("That file was not found. Program terminating...");
e.printStackTrace();
}
}
Any help would be appreciated thanks.
If i understood correctly, you just have to create a new Scanner, one for each file.
Like that:
public static void main(String[] args) {
int[] mergedArray = {};
Scanner input = new Scanner(System.in);
System.out.println("Enter the name of your first file (including file extension): ");
String filename1 = input.next();
System.out.println("Enter the name of your second file (including file extension): ");
String filename2 = input.next();
int[] firstArray = null;
int[] secondArray = null;
try {
Scanner in = new Scanner(new File(filename1));
int count = in.nextInt();
firstArray = new int[count];
firstArray[0] = count;
for (int i = 0; in.hasNextInt() && count != -1 && i < count; i++) {
firstArray[i] = in.nextInt();
}
} catch (final FileNotFoundException e) {
System.out.println("That file was not found. Program terminating...");
e.printStackTrace();
}
try {
Scanner in2 = new Scanner(new File(filename2));
int count = in2.nextInt();
secondArray = new int[count];
secondArray[0] = count;
for (int i = 0; in2.hasNextInt() && count != -1 && i < count; i++) {
secondArray[i] = in2.nextInt();
}
} catch (final FileNotFoundException e) {
System.out.println("That file was not found. Program terminating...");
e.printStackTrace();
}
// do the merge operation with the 2 arrays
}
Try this
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.util.Scanner;
import static java.lang.System.*;
import java.util.Collection;
import java.util.Collections;
import java.util.ArrayList;
import java.util.Arrays;
public final class TwoSourceMergeOne{
public static void main(String[] args) {
Integer [] mergedArray = null;
try(Scanner console = new Scanner(in)){
out.println("Enter the Source file names (including file extensions) : ");
out.print(">> ");
String sourceX = console.next();
out.print("\n>> ");
String sourceY = console.next();
Path sourceXPath = Paths.get(sourceX);
Path sourceYPath = Paths.get(sourceY);
if(!Files.exists(sourceXPath,LinkOption.NOFOLLOW_LINKS) || !Files.exists(sourceXPath,LinkOption.NOFOLLOW_LINKS)){
out.println("Sorry. Some source files are missing. Please make sure that they are available !");
return;
}
Scanner xInput = new Scanner(new FileInputStream(sourceXPath.toFile()));
Scanner yInput = new Scanner(new FileInputStream(sourceYPath.toFile()));
Collection<Integer> sourceXData = new ArrayList<>();
Collection<Integer> sourceYData = new ArrayList<>();
while(xInput.hasNextInt()) sourceXData.add(xInput.nextInt());
while(yInput.hasNextInt()) sourceYData.add(yInput.nextInt());
if(!sourceXData.isEmpty() && !sourceYData.isEmpty()){
Integer [] soure_x_array = sourceXData.toArray(new Integer[sourceXData.size()]);
Integer [] source_y_array = sourceYData.toArray(new Integer[sourceYData.size()]);
mergedArray = new Integer[soure_x_array.length+source_y_array.length];
int index = 0;
for(int x : soure_x_array) mergedArray[index ++] = x;
for(int y : source_y_array) mergedArray[index ++] = y;
out.printf("The merged array is = %s",Arrays.toString(mergedArray));
}else{
out.println("Sorry. No input data !!!");
}
}catch(IOException cause){ cause.printStackTrace();}
}
}
The two source files should be in the same folder as the program.

Reading text from .text file and storing in array

so basically I only know how to read integers and store them in an array, but what about both Integers and words? Here is my code for doing just the integers from an array from an earlier time, the method is readFileAndReturnWords. How could I change it to read both integers and words as well?
import java.util.Scanner;
import java.util.InputMismatchException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class WordsNsuch {
public static void main(String [ ] commandlineArguments){
//Error message when arg is blank
if(commandlineArguments.length == 0) {
System.err.println("You did not enter anything");
System.exit(0);
}
String[] array = readFileAndReturnWords(commandlineArguments[0]);
sortAndPrintTheArray(array, commandlineArguments[0]);
}
//RIGHT HERE GUYS
public static String readFileAndReturnWords(String filename){
String[] temp = new String[10000];
int i = 0;
//connects file
File file = new File(filename);
Scanner inputFile = null;
try{
inputFile = new Scanner(file);
}
//When arg is mistyped
catch(FileNotFoundException Exception1) {
System.out.println("File not found!");
System.exit(0);
}
//counts the amount of strings
if (inputFile != null) {
try {
while (inputFile.hasNext()) {
try {
temp[i] = inputFile.nextInt();//This is a problem
i++;
} catch (InputMismatchException Exception2) {
inputFile.next();
}
}
}
finally {
inputFile.close();
}
String[] array = new String[i];
System.arraycopy(temp, 0, array, 0, i);
return array;
}
return new String[] {};
}
public static void sortAndPrintTheArray(String [] array, String filename){
Sorting.display = false;
Sorting.insertionSort(array, 0, array.length-1);//figure out how to get the last word later
System.out.println("ASCII listing of words in file:\"" + filename + "\" = " + array.length);
for (int i = 0; i < array.length; i++) {
System.out.println("index = " + i + "," + " element = " + array[i]);
}
}
}
I'm not going into your code but here is an example of how to read both numbers and words :
//while there's anything including numbers and words
while(textfile.hasNext())
{
//if there's a number, read it!
if(textfile.hasNextInt())
{
int number = textfile.nextInt(); //it can be double, float..
}
else
textfile.next()
String word1 = textfile.hasNext();
String word2 = textfile.hastNext();
f(textfile.hasNextInt())
{
int number2 = textfile.nextInt(); //it can be double, float..
}
else
textfile.next()
.......
}
Anytime if there's a number, try if-else statement ("else" statement depends on how big and how full your textfile is with numbers and letters) but when after a number there follows a String use else statement similar to the else statement in the code that I've mentioned; when there's a String, just read that with textfileName.hasNext() w/o any conditionals. Any question, do not hesitate to ask!
Here is a little code snippet to help you out, I have based it on your code.
I would handle the arrays slightly differently but I just want to point you in the right direction, not do the work for you.
This will create two arrays: ints and strs one staininging the integers and one containing the strings.
int[] ints = new int[10000];
String[] strs = new String[10000];
int i = 0;
int j = 0;
File file = new File(filename);
Scanner inputFile = null;
try {
inputFile = new Scanner(file);
} catch(FileNotFoundException Exception1) {
System.out.println("File not found!");
System.exit(0);
}
try {
while (inputFile.hasNext()) {
if (inputFile.hasNextInt()) {
ints[i++] = inputFile.nextInt();
} else {
strs[j++] = inputFile.next();
}
}
}
Hope this helps!

UPDATED: Reading text file into a byte array

For a homework assignment, I need to create a class that that can read and write Byte arrays to/from a file. I have successfully created classes that can read and write CSV and text, however I am having some difficulty, when it comes to arrays. The code below is features the class that I have written. It is largely based on my CSV class, the FileInput class http://www.devjavasoft.org/SecondEdition/SourceCode/Share/FileInput.java) and FileOutput Class (http://www.devjavasoft.org/SecondEdition/SourceCode/Share/FileOutput.java).
When running the program to read a text file I get the following error message:
"Exception in thread "main" java.lang.NullPointerException
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:101)
at java.io.FileReader.<init>(FileReader.java:58)
at com.gc01.FileManager.FileInput.<init>(FileInput.java:22)
at com.gc01.FileManager.ByteManager.readByte(ByteManager.java:28)
at com.gc01.FileManager.ByteManager.main(ByteManager.java:85)"
And my code:
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class ByteManager {
public String getByteFile(){
Scanner sc = new Scanner (System.in);
System.out.println("Please enter the file directory of the chosen txt file?");
System.out.println("For Example: /Users/UserName/Downloads/FileName.txt");
///Users/ReeceAkhtar/Desktop/FileName.txt
final String fileName = sc.nextLine();
System.out.println("How many columns are in the file?");
final int columns = sc.nextByte();
System.out.println("How many rows are in the file?");
final int rows = sc.nextByte();
return fileName;
}
public void readByte(final String fileName, int columns, int rows){
FileInput in = new FileInput(fileName);
int [] [] data = new int[rows] [columns];
String [] line;
for (int i = 0; i < rows; i++){
line = in.readString().split("\t");
for (int j = 0; j < columns; i++){
data [i][j] = Byte.parseByte(line[j]);
}
}
System.out.println("******File Read*****");
}
public String chooseFileOutput(){
Scanner sc = new Scanner (System.in);
System.out.println("Please enter the file directory for the output of the chosen file");
System.out.println("For Example: /Users/UserName/Downloads/FileName.txt");
///Users/ReeceAkhtar/Desktop/GeoIPCountryWhois.csv
final String fileNameOUT = sc.nextLine();
System.out.println("How many columns are in the file?");
final int columnsOut = sc.nextByte();
System.out.println("How many rows are in the file?");
final int rowsOut = sc.nextByte();
return fileNameOUT;
}
public void writeByte(final String fileNameOUT, int columnsOut, int rowsOut){
FileOutput createData = new FileOutput (fileNameOUT);
int newData = 0;
System.out.println("Enter data. To finish, enter 'TERMINATE_FILE'");
while(!"TERMINATE_FILE".equals(newData)){
Scanner input = new Scanner (System.in);
int [] [] data = new int[rowsOut] [columnsOut];
String [] line = null;
for (int i = 0; i < rowsOut; i++){
createData.writeInteger(newData = input.nextByte());
System.out.println("\t");
for (int j = 0; j < columnsOut; i++){
data [i][j] = Byte.parseByte(line[j]);
}
}
createData.close();
}
}
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
final ByteManager object = new ByteManager ();
System.out.println("1 for Read File, 2 for Write file");
String choice = in.nextLine();
if("1".equals(choice)){
object.getByteFile();
object.readByte(null, 0, 0);
} else if ("2".equals(choice)){
object.chooseFileOutput();
object.writeByte(null, 0, 0);
} else{
System.out.println("Goodbye!");
System.exit(0);
}
}
}
UPDATE
Thank you for your comments and advice below, I have now run into a another problem that I can not work out. I have re-written my readByte method. However when I now run it, I no longer get compiler errors (thanks to your advice), however I can not get the contents of the file to print. Instead the console just displays "File Read". I have studied various resources yet I can not find the solution. I am sure it is a simple mistake somewhere. The contents of the file I am trying to read is also below.
public String getByteFile(){
Scanner sc = new Scanner (System.in);
System.out.println("Please enter the file directory of the chosen txt file?");
System.out.println("For Example: /Users/UserName/Downloads/FileName.txt");
///Users/ReeceAkhtar/Desktop/FileName.txt
final String fileName = sc.nextLine();
System.out.println("How many columns are in the file?");
final int columns = sc.nextInt();
System.out.println("How many rows are in the file?");
final int rows = sc.nextInt();
return fileName;
}
public void readByte(final String fileName, int rows,int columns){
BufferedReader br = null;
String[] line;
String splitBy = "\t";
int [][] data = new int[rows] [columns];
try {
br = new BufferedReader(new FileReader(fileName));
for (int i = 0; i < rows; i++){
line = br.toString().split(splitBy);
for (int j = 0; j < columns; j++){
data[i] [j] = Integer.parseInt(line[j]);
System.out.println(data[i][j]);
}
}
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("*****File Read*****");
}
File Contents (separated by tab)
123 6565
123 6564
123 6563
123 6562
This code is the source of the error
object.readByte(null, 0, 0);
The parameter null is invalid state for FileInput. It should be a file name string.
You are passing null argument to readByte() from main()
object.readByte(null, 0, 0);
And in readByte()
FileInput in = new FileInput(fileName); //here it throws NPE
Pass valid file name.
NullPointerException
public class NullPointerException
extends RuntimeException
Thrown when an application attempts to use null in a case where an object is required. These include:
Calling the instance method of a null object.
Accessing or modifying the field of a null object.
Taking the length of null as if it were an array.
Accessing or modifying the slots of null as if it were an array.
Throwing null as if it were a Throwable value.

Categories