Я работаю над программой чтения файлов, которая берет файл «PovertyData.txt», разбивает его на части и находит процентное соотношение между двумя числами. Я хочу записать его в двоичный файл, а затем вывести его в другой файл, используя два основных метода. Однако, когда я запускаю первый основной метод, я получаю следующее исключение:
Exception in thread "main" java.lang.NumberFormatException: empty String
at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842)
at java.base/jdk.internal.math.FloatingDecimal.parseFloat(FloatingDecimal.java:122)
at java.base/java.lang.Float.parseFloat(Float.java:461)
at fileReader.toText(fileReader.java:151)
at fileReader.splitFile(fileReader.java:128)
at Main.main(Main.java:32)
Первый класс «Main» имеет следующий код:
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
public class Main {
public static void main(String []args) throws IOException {
int lineCharCount = 130; //length of each line in file
int outputCharCount = 28; //length of each output line
String fileName = "PovertyData.txt"; //name of the imported file
try (
RandomAccessFile binDat = new RandomAccessFile("povertyBinary.dat", "rw");
) {
File povertyFile = new File(fileName); //importing the file
int [] includeData = {0, 1, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107}; //all the data values needed for the output
int [] percentParameterOne = {100, 107}; //child poverty population character locations
int [] percentParameterTwo = {91, 98}; //total child population character locations
fileReader readFiles = new fileReader(lineCharCount, outputCharCount);
readFiles.setIncludeData(includeData);
readFiles.setPercentOne(percentParameterOne[0], percentParameterOne[1]);
readFiles.setPercentTwo(percentParameterTwo[0], percentParameterTwo[1]);
binDat.writeChars(readFiles.splitFile(povertyFile));
}
catch (java.io.IOException ex) {
ex.printStackTrace();
}
}
}
Класс «fileReader» имеет следующий код:
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Scanner;
public class fileReader {
int lineCharCount; // number of spaces per line in the input
int outputCharCount; // number of spaces the output will use
int[] includeData; // data value places that will be included into the output
String returnText = ""; // text that will be returned
int[] percentDataOne = new int[2]; // the first set of data that will be the numerator of the percentage
int[] percentDataTwo = new int[2]; // the second set of data that will be the denominator of the percentage
// CONSTRUCTORS
public fileReader() {
this.lineCharCount = 0;
this.outputCharCount = 0;
this.includeData = new int[outputCharCount];
this.percentDataOne[0] = 0;
this.percentDataOne[1] = 0;
this.percentDataTwo[0] = 0;
this.percentDataTwo[1] = 0;
} // default constructor that sets everything to default values
public fileReader(final int lineCharCount, final int outputCharCount) {
this.lineCharCount = lineCharCount;
this.outputCharCount = outputCharCount;
this.includeData = new int[outputCharCount];
} // constructor to set everything to custom values
// SETTER METHODS
public void setIncludeData(final int[] inputArray) {
for (int i = 0; i < this.includeData.length; i++) {
this.includeData[i] = inputArray[i];
}
}
public void setoutputCharCount(final int outputCharCount) {
this.outputCharCount = outputCharCount;
}
public void setlineCharCount(final int lineCharCount) {
this.lineCharCount = lineCharCount;
}
public void setPercentOne(int dataOne, int dataTwo) {
this.percentDataOne[0] = dataOne;
this.percentDataOne[1] = dataTwo;
}
public void setPercentTwo(int dataOne, int dataTwo) {
this.percentDataTwo[0] = dataOne;
this.percentDataTwo[1] = dataTwo;
}
// GETTER METHODS
public int getlineCharCount() {
return this.lineCharCount;
}
public int getoutputCharCount() {
return this.outputCharCount;
}
public int[] getIncludeData() {
return this.includeData;
}
// CUSTOM METHODS
public String splitFile(final File file) throws IOException {
int fileLength = 0;
/* try (
Scanner counter = new Scanner(new FileReader(file))
) {
while (counter.hasNextLine()) {
counter.nextLine();
fileLength++;
} //counts number of lines in the file
} //automatically closes the scanner
*/ //Original code to count lines in the file (didn't work because it made the second scanner not scan anything and we got a NoSuchElementException)
final ArrayList<String> allLines = (ArrayList<String>) Files.readAllLines(file.toPath()); // Makes an ArrayList "allLines" which finds the path of the file, locates the file, reads all the lines of the file "file" and copies them into individual array elements
/*
* Creates ArrayList of Strings (flexible array that I don't need to specify the
* size/length of) Finds the path name of "file" Reads all the lines of "file"
* Sets the ArrayList of Strings to be the same as every single line of "file"
*/
fileLength = allLines.size(); // length (or size) of allLines should be the number of lines in the file
final String[] inArray = new String[fileLength]; // array that will contain every line in the file
allLines.toArray(inArray); //reads all contents of the ArrayList to the array
String [] secArray = new String[this.lineCharCount]; // array that will contain every character of the line of inArray
try (
final Scanner input = new Scanner(file);
) {
for (int i = 0; i < fileLength; i++) {
inArray[i] = input.nextLine();
} //puts all the lines of the file into a massive array
} //automatically closes the scanner
final String[][] outArray = new String[fileLength][this.lineCharCount]; // output array that will betranslated into text, has to be placed here for the .length attribute of inArray to be correct
for (int h = 0; h < fileLength; h++) {
//System.out.println("Reading..."); //debug
secArray = inArray[h].split(""); //splits the line into portions
for (int k = 0; k < this.lineCharCount; k++) {
outArray[h][k] = secArray[k]; // h = # rows, k = # columns
//System.out.println("Writing..."); //debug
}
} // nested loops to transfer information into the 2D array
toText(outArray, fileLength, secArray);
return this.returnText;
} // massive method that splits a file into individual parts
public void toText(final String[][] array, final int arrayLength, final String [] otherArray) {
String percentStringOne = "";
String percentStringTwo = "";
float percentFloat;
for (int i = 0; i < arrayLength; i++) {
//System.out.println("Making Line"); //debug
for (int j = 0; j < this.includeData.length; j++ ) {
if (j > this.percentDataOne[0] && j < this.percentDataOne[1]) {
percentStringOne += otherArray[j];
} //an if statement that collects the number within the parameters defined in percentDataOne
if (j > this.percentDataTwo[0] && j < this.percentDataTwo[1]) {
percentStringTwo += otherArray[j];
} //an if statement that collects the number within the parameters defined in percentDataTwo
this.returnText += array[i] [this.includeData[j]];
//System.out.println("Writing Data"); //debug
}
percentFloat = Float.parseFloat(percentStringOne) / Float.parseFloat(percentStringTwo);
this.returnText += " " + percentFloat + " \n";
} //method turns the 2D array into a neat output
//if includeData = {0, 2} and outArray = {{0, 2, 3}{8, 9, 14}} then returnText will equal to 0 3 \n 8 14
} //method that converts the 2D array into readable text
}
Размер PovertyData.txt превышает 10 000 строк, вот выдержка из него.
01 00190 Alabaster City School District 31754 6475 733 USSD13.txt 24NOV2014
01 00005 Albertville City School District 21522 4010 1563 USSD13.txt 24NOV2014
01 00030 Alexander City City School District 17292 2719 1158 USSD13.txt 24NOV2014
01 00060 Andalusia City School District 9044 1512 471 USSD13.txt 24NOV2014
01 00090 Anniston City School District 22759 3304 1122 USSD13.txt 24NOV2014
01 00100 Arab City School District 8238 1491 250 USSD13.txt 24NOV2014
01 00120 Athens City School District 23494 3767 770 USSD13.txt 24NOV2014
01 00180 Attalla City School District 6019 971 283 USSD13.txt 24NOV2014
01 00210 Auburn City School District 57441 7120 994 USSD13.txt 24NOV2014
01 00240 Autauga County School District 55246 10643 1855 USSD13.txt 24NOV2014
01 00270 Baldwin County School District 195540 32652 6171 USSD13.txt 24NOV2014
01 00300 Barbour County School District 14124 1769 759 USSD13.txt 24NOV2014
01 00330 Bessemer City School District 27510 4765 2009 USSD13.txt 24NOV2014
01 00360 Bibb County School District 22512 3590 1096 USSD13.txt 24NOV2014
01 00390 Birmingham City School District 212631 30718 12740 USSD13.txt 24NOV2014
01 00420 Blount County School District 51246 9201 2218 USSD13.txt 24NOV2014
01 00012 Boaz City School District 9619 1742 464 USSD13.txt 24NOV2014
01 00450 Brewton City School District 5354 866 279 USSD13.txt 24NOV2014
01 00480 Bullock County School District 10639 1565 684 USSD13.txt 24NOV2014
01 00510 Butler County School District 20265 3494 1430 USSD13.txt 24NOV2014
Похоже, что мои попытки прочитать определенные числа не работай. Что я могу сделать, чтобы это исправить?