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.
Related
All I am trying to do is create an array from numbers in a file... I'm pretty new to java so it may not be the most efficient way but I'm going off limited knowledge for now.
When I run it, I get the following message:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at CreateArray.main(CreateArray.java:27)
Here is my feeble attempt at the code:
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
public class CreateArray
{
public static void main(String[] args) throws IOException
{
File file = new File("Numbers.txt");
Scanner inputFile = new Scanner(file);
// Find the number of lines in the file
int count = 0;
while (inputFile.hasNextLine())
{
String str = inputFile.nextLine();
count++;
}
// Create array
double[] numbers = new double[count];
// Add numbers to array
String str;
while (inputFile.hasNextLine());
{
for (int i = 0; i < count; i++)
{
str = inputFile.nextLine();
numbers[i] = Double.parseDouble(str);
}
}
// Display array
for (int i = 0; i < numbers.length; i++)
System.out.print(numbers[i] + " ");
}
}
When you write inputFile.hasNextLine() in your code using scanner, You have actually read a line from the file. As #tima said, you completed reading the file in the first while loop. Try looking at this java: about read txt file into array
Use Collection like ArrayList .So at time of File reading you don't need to declare size of array.
File file = new File("Numbers.txt");
Scanner inputFile = new Scanner(file);
List<Double> myList = new ArrayList<Double>();
while (inputFile.hasNextLine()) {
String str = inputFile.nextLine();
try {
myList.add(Double.parseDouble(str));
} catch (NumberFormatException e) {
// TODO: handle exception
}
}
for (Double data : myList) {
System.out.println(data);
}
And if you need array type ,then use this :-
Double data[] = new Double[myList.size()];
myList.toArray(data);
for (int i = 0; i < data.length; i++) {
System.out.println(data[i]);
}
I have written a spellchecker program that checks the spelling of all words in a file. It should read each word of a file and check whether it is contained in a word list. The program should write the incorrect words to a file and I have received an error message on lines 57-58, saying "type mismatch between void to String" and when I ran it on eclipse, I got an unresolved compilation problem" error. What am I doing wrong so it can run smoothly on both Eclipse & on the command line? Here's the code:
import java.util.*;
import java.io.*;
public class SpellChecker {
public static void readDict(){
File file = new File ("words.txt");
ArrayList <String> array = new ArrayList <String> ();
try{
Scanner input = new Scanner (file).useDelimiter("[A-Za-z]");
while (input.hasNext()){
String line = input.nextLine();
String [] wordArray = line.split(" ");
for(String str : wordArray){
array.add(str);
}
}
input.close();
}
catch(FileNotFoundException e){
System.out.println("File is not found.");
System.exit(1);
}
return;
}
public static void readFile(){
File file = new File ("mary.txt");
String [] array;
String [] array2 = null;
try{
Scanner input = new Scanner (file);
int i = 0;
array = new String [10];
while(i < array.length && input.hasNext()){
String story = input.nextLine();
String[] storyarray = story.split(" ");
array2[i] = storyarray[i];
i++;
for(i = 0; i < array2.length; i++){
System.out.println(array2[i]);
}
input.close();
}
}
catch(FileNotFoundException e){
System.out.println("File cannot be found.");
System.exit(1);
}
}
public static void main(String[] args) {
args[0] = readDict();
args[1] = readFile();
if(args == 4){
System.out.println(args[0]);
System.out.println(args[1]);
}
}
public static Scanner input = new Scanner(System.in);
}
So I have created this method which at the end displays the whole line because i am displaying the array after converting and editing it. So my Question is how can i know overwrite the array to the same line i grabbed it from. thanks in advance and here is my code.
public void getData(String path, String accountNumber) {
try {
FileInputStream fis = new FileInputStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
System.out.println("Please Enter the Deposit amount That you would like to add.");
Scanner sn = new Scanner (System.in);
int add = sn.nextInt();
String str;
while ((str = br.readLine()) != null) {
if (str.contains(accountNumber)) {
String[] array = str.split(" ");
int old = Integer.parseInt(array[3]);
int Sum= old + add;
String Sumf = Integer.toString(Sum);
array[3] = Sumf;
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);}
break;
}
}
} catch (Exception ex) {
System.out.println(ex);
}
}
i am using string accountNumber to grab the specific line that i need. after getting the line i am changing it to an array while splitting the index with str.split(" "); . After that i know that i need to edit index number [3]. so i do so and then i put it back into the array. the final thing i need to do is to right the array back now.
You can keep track of the input from the file you are reading and write it back with the modified version.
public void getData(String path, String accountNumber) {
try {
FileInputStream fis = new FileInputStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
System.out.println("Please Enter the Deposit amount That you would like to add.");
Scanner sn = new Scanner (System.in);
int add = sn.nextInt();
String line; // current line
String input = ""; // overall input
while ((line = br.readLine()) != null) {
if (line.contains(accountNumber)) {
String[] array = line.split(" ");
int old = Integer.parseInt(array[3]);
int Sum= old + add;
String Sumf = Integer.toString(Sum);
array[3] = Sumf;
// rebuild the 'line' string with the modified value
line = "";
for (int i = 0; i < array.length; i++)
line+=array[i]+" ";
line = line.substring(0,line.length()-1); // remove the final space
}
// add the 'line' string to the overall input
input+=line+"\n";
}
// write the 'input' String with the replaced line OVER the same file
FileOutputStream fileOut = new FileOutputStream(path);
fileOut.write(input.getBytes());
fileOut.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
This is how i understand the question that you have a file you will read it line by line and will make some changes and want to write it again at the same position. Create a new temp file and write the contents to the temp file, if changed write the changed result if not write it as it is.
And at last rename the temp to your original file name
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.
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.