How to read in integers from a file in Java - java

Okay so I wanted to read in the integers I have along with the strings in a file. So far I have this code and I keep getting an error. I have this in my text file: Grey:30
Black:40
I'm trying to read in the strings along with the integers because I want to set the integers as points worth for the string (color)
while (strike!=3){
Scanner name1 = new Scanner(System.in);
System.out.println("Enter A color");
String nameTaken = name1.next();
while(filechecker.hasNextLine()){
list.add(filechecker.nextLine());
}
String line =filechecker.nextLine();
String[] details = line.split(":");//checks for the integer next to the color
if((list.contains(nameTaken))&&(filechecker.hasNextInt())){
int points = Integer.parseInt(details[2]);
System.out.println("The Answer Exists!! You Got " +details[2]);

You don't indicate what error you're getting, but I can see from the following code, you're likely getting a NullPointerException or something similar.
Edit: Seems you're getting the NoSuchElementException because no lines remain to be read.
This block of code loops through your filechecker and reads all lines into a list, until no more lines remain. The line immediately following the while block attempts to read another line from it, which it won't find because you've read them all (it will return null). The line where you try to split will throw an exception because of this.
while(filechecker.hasNextLine()){
list.add(filechecker.nextLine());
}
String line =filechecker.nextLine(); // <-- this line is throwing it. Don't use it here, use your list or do your work in the while loop instead.
String[] details = line.split(":");//checks for the integer next to the color
Instead of operating on the filechecker after your while, loop, use your list. Or better yet, do all your work in the while loop instead.

It might be easier to use a HashMap to store your data:
HashMap<String, Integer> colorData = new HashMap<String, Integer>();
You can then use ObjectOutputStream and ObjectInputStream to write and read the file:
void write(String fileName) {
FileOutputStream fileOut = new FileOutputStream(fileName);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(colorData);
}
void read(String fileName) {
ObjectInputStream in = null;
try {
fileIn = new FileInputStream(fileName);
in = new ObjectInputStream(fileIn);
colorData = (HashMap<String, Integer>) in.readObject();
} catch (Exception e) {
e.printStackTrace();
}finally {
if(objectinputstream != null)
objectinputstream .close();
}
}

Related

BufferedReader reads just one line in an multiple line file

I tried to archive that a multiline file will be read from an BufferedReader. But this BufferedReader reads just one line and exiting his while(). Before he can read this, another method of the same class should've been written in this file (not at the same time), mostly more than one line. The file contains different types of variables, such as int[], int, double[], String. At the end of one object, or nearly just the data that I've to collect that I can re-calculate the whole object, the ObjectOutputStream pastes "\n". I just write parsed Strings in this file.
In my case, it's a workaround for the ObjectInputStream, cause this stream throws an EOFException every time. For those who don't know the EOFException: it will be thrown if the reader reaches end of file while reading.
I tried to:
set the input string for the BufferedReader to another line
.close() the Reader and make it new
set while(1)
write other Datatypes, such as the whole Object
but all without any changes. The BufferedReader reads just one line and the ObjectInputStream throws EOFException.
LinkedList<SomeAnotherSelfMadeClass> list;
File file = new File(fullPath) // fullPath = absolute path to the file
FileInputStream fileInputStream;
BufferedReader bufferedReader;
public static LinkedList<SomeAnotherSelfMadeClass> readFile()
{
list = new LinkedList<SomeAnotherSelfMadeClass>();
fileInputStream = new FileInputStream(file); // could be FileReader
bufferedReader = new BufferedReader(fileInputStream);
String helper, anotherHelper;
while ((helper = bufferedReader.readLine()) != null)
{
while ((anotherHelper = scanner.hasNext()) != null)
// here's some code with scanner-things, it shouldn't be necessary to
// know. In fact the scanner help to gather the data from the file and
// create an object of SomeAnotherSelfMadeCLass and put it into the list
}
bufferedReader.close();
fileInputStream.close();
return list;
}
What can I do that I can read all lines of the file and re-calcuate my objects that are pasted in there?
I don't know either; it is better to work with the ObjectInputStream or with the BufferedReader? What can I do that the ObjectInputStream don't throws the EOFException (every time I worked with the ObjectInputStream I wrote the whole Object via ObjectOutputStream)?
P.S.: I don't have internet atm at home, so it could take a while that I'm able to answer.
Try with this structure of code..
BufferedReader objReader = null;
public static LinkedList<SomeAnotherSelfMadeClass> readFile()
{
list = new LinkedList<SomeAnotherSelfMadeClass>();
try {
objReader = new BufferedReader(new FileReader(fullPath));
while ((helper= objReader.readLine()) != null) {
...........
System.out.println(helper);//just for checking
while ((anotherHelper = scanner.hasNextLine()) != null){
.....
....
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (objReader != null)
objReader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
I'm a little idiot, you have to know.
The second while() had the condition (anotherHelper = scanner.next()) != null, not that what I stated before.
But I managed to get another outputs, even I tried this before (it seems that I'd misstyped at any point);
I set the first while() to true, test helper to break out of the while() and deleted the second while:
while(true)
{
helper = bufferedReader.readLine();
if (helper.equals(null))
break;
// making things with the scanner
}
It seems that the compiler had a problem with this double-while. And optimized it wrong; I think he made
while (((helper = bufferedReader.readLine() != null) && (helper = scanner.nextLine()) != null)
out of this peace of code. That would explain why it only run once and returns true if I test it with System.out.println(scanner.hasNext(); and System.out.println(scanner.hasNextLine(); BEFORE the second while, but in it he returns not even false.

How read big text file and work with it in Java

I have a large text file, and i want read it, when i try do it without any operations like add some text from this file to List it read file maximum to one minute but when i try add some text to arrayList and next i want do some operations it is too slowly, do you know how can i read this data and use it?
This is my code:
public class ReaderTEst {
public static void main(String[] args) throws IOException {
List<String> graphList = new ArrayList<>();
List<String> edgeList = new ArrayList<>();
FileInputStream inputStream = null;
Scanner sc = null;
try {
inputStream = new FileInputStream("myText.txt");
sc = new Scanner(inputStream, "UTF-8");
while (sc.hasNextLine()) {
String line = sc.nextLine();
line = line.replace("\uFEFF", "");//i use UTF-8 file so I need delete unneeded character
if (Character.isWhitespace(line.charAt(0))) {
edgeList.add(line.trim());
} else {
graphList.add(line);
}
}
if (sc.ioException() != null) {
throw sc.ioException();
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (sc != null) {
sc.close();
}
}
}
}
It takes to many time, do you know how it could be faster? I have file txt with 600 MB
When i change :
List<Integer> graphList = new ArrayList<>(1);
int i = 0;
while (sc.hasNextLine()) {`String line = sc.nextLine();`
line = line.replace("\uFEFF", "");//i use UTF-8 file so I need delete unneeded character
graphList.add(i++);
}
i works, but when i want put string it takes too long time
You should use BufferedReader.readLine(). You can read millions of lines per second with that. Scanner is overkill for what you're doing.
BUT \uFEFF is not text. Is this really a text file? Is that a BOM marker? in which case it will only be at the beginning of the first line: no need to scan for it in every line.
Your main issues are the following:
List<String> graphList = new ArrayList<>();
List<String> edgeList = new ArrayList<>();
You should initialize each List with an initial capacity so that the JVM does not need to automatically expand the backing array.
line = line.replace("\uFEFF", "");
This will also slow down your program. How often is \uFEFF in each line? I would check if the line contains \uFEFF before attempting to replace it.
Other than that, there's not much else to optimize; maybe you can utilize a FileChannel to read the file, but that's about it.
First of all I advise to use the LinkedList realization of List because of architectual features. Thus the ArrayList is built-on arrays, the LinkedList consists on Nodes. The ArrayList creates new bigger arrays and copy old one the new one, then it is reach some capasity. Oracle has perfect documentation about this, I recommend it to you LinkedList
ArrayList

Error with file reader [duplicate]

This question already has an answer here:
What does "Incompatible types: void cannot be converted to ..." mean?
(1 answer)
Closed 6 months ago.
I'm getting an error with
PersonsInfoData[i] = PersonsInfoin.setPersonsInfo(temp[0],temp[1],temp[2],temp[3],temp[4]);
"Incompatible types: void cannot be coverted to PersonsInfo"
public void readFile(String fileName)
{
// Try to read in the data and if an exception occurs go to the Catch section
try
{
FileInputStream fstream = new FileInputStream(fileName);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
int i = 0; // i is used as the line counter
String line; // line is used to temporarily store the line read in from the data file
// Read a line from the data file into the buffer and then check whether
// it is null. The while loop continues until a line read in is null.
while ((line = br.readLine()) != null)
{
// Split the line of data (from the text file) and put each entry into the
// temporary array - temp[]
String[] temp = line.split(",");
// Save each entry into its respective PCDataRecord object.
PersonsInfoData[i] = PersonsInfoin.setPersonsInfo(temp[0],temp[1],temp[2],temp[3],temp[4]);
i++; // Increment i so we can keep a count of how many entries have been read in.
}
numberOfEntries = i; // Set numberOfEntries equal to i, to remember how many entries are now in the array
br.close(); // Close the BufferedReader
in.close(); // Close the DataInputStream
fstream.close(); // Close the FileInputStream
}
catch (Exception e)
{
System.err.println("Error Reading File: " + e.getMessage());
}
}
this is a setter statement:
PersonsInfoin.setPersonsInfo(temp[0],temp[1],temp[2],temp[3],temp[4]);
so, not all setters return objects, in your case that method returns returns nothing (void) making your statement equivalent to doing:
PersonsInfoData[i] = void
which is invalid...
I guess you are trying to write the values to PersonsInfoData[i]. If yes, then replace the line with -
PersonsInfoData[i].setPersonsInfo(temp[0],temp[1],temp[2],temp[3],temp[4]);

Read a single file with multiple BufferedReaders

I'm working on a program that needs to update a line that depends its value on the result of a line that goes read after. I thought that I could use two BufferedReaders in Java to position the reader on the line to update while the other one goes for the line that fixes the value (it can be an unknown number of lines ahead). The problem here is that I'm using two BufferedReaders on the same file and even if I think I'm doing right with the indexes the result in debug doesn't seem to be reliable.
Here's the code:
String outFinal
FileName=fileOut;
File fileDest=new File(outFinalFileName);
try {
fout = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(fileDest)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
FileReader inputFile=null;
try {
inputFile = new FileReader(inFileName);
} catch (FileNotFoundException e2) {
e2.printStackTrace();
}
BufferedReader fin = new BufferedReader(inputFile);
BufferedReader finChecker = new BufferedReader(inputFile); //Checks the file and matches record to change
String line="";
String lineC="";
int lineNumber=0;
String recordType="";
String statusCode="";
try {
while ((lineC = finChecker.readLine()) != null) {
lineNumber++;
if (lineNumber==1)
line=fin.readLine();
recordType=lineC.substring(0,3);//Gets current Record Type
if (recordType.equals("35")){
while(!line.equals(lineC)){
line=fin.readLine();
if (line==null)
break;
fout.write(line);
}
}else if (recordType.equals("32")){
statusCode=lineC.substring(4,7);
if(statusCode.equals("XX")){
updateRecordLine(line,fout);
}
}
}
returnVal=true;
} catch (IOException e) {
e.printStackTrace();
}
Thanks in advance.
Well, the BufferedReader only reads stuff, it doesn't have the ability to write data back out. So, what you would need is a BufferedReader to get stuff in, and a BufferedWriter that takes all the input from the BufferedReader, and outputs it to a temp file, with the corrected/appended data.
Then, when you're done (i.e. both BufferedReader and BufferedWriter streams are closed), you need to either discard the original file, or rename the temp file to the name of the original file.
You are basically copying the original file to a temp file, modifying the line in question in the temp file's output, and then copying/renaming the temp file over the original.
ok, i see some problem in your code exactly on these lines-->
recordType=lineC.substring(0,3);//Gets current Record Type
if (recordType.equals("35")){
if you see on the first line, you are getting the substring of recordType into recordType. Now recordType length is 3. If at all the recordType has only 2 characters, then substring throws arrayIndexOutOfBoundsException. So when no runtime exceptions, its length is 3 and on the next line you are calling the equals method that has a string with 2 characters.
Will this if block ever run ?

DataInputStream for input text files?

I am learning to read and write in Java and am stuck with a simple exercise. The program reads from 2 txt files that each contain numbers in rows. It writes to an output file the result of the multiplication of each row of numbers. eg. file 1 row 1 : 10, file 2 row 1: 2 , the program should write 20 to the output file. My code seems to have something missing somewhere. The output file is created but nothing is written to it. Any ideas?
import java.io.*;
import java.util.*;
class ReadWriteData
{
public static void main(String[] args) throws Exception
{
//create ouput file
PrintWriter output = new PrintWriter("output2.txt");
DataInputStream file1 = new DataInputStream(new FileInputStream(args[0]));
DataInputStream file2 = new DataInputStream(new FileInputStream(args[1]));
try
{
// read data from file
while (true)
{
double number1 = file1.readDouble();
double number2 = file2.readDouble();
double result = number1 * number2 ;
output.println(result);
}
}
catch (IOException e)
{
System.err.println("Error");
System.exit(1);
}
output.close() ;
}
}
Here is an implementation with a BufferedReader that works.
public static void main(String[] args) throws Exception {
//create ouput file
PrintWriter output = new PrintWriter("output2.txt");
BufferedReader file1 = new BufferedReader(new FileReader("numbers1.txt"));
BufferedReader file2 = new BufferedReader(new FileReader("numbers2.txt"));
try {
// read data from file
while (true) {
String number1AsString = file1.readLine();
String number2AsString = file2.readLine();
if (number1AsString == null || number2AsString == null) {
break;
}
double number1 = Double.parseDouble(number1AsString);
double number2 = Double.parseDouble(number2AsString);
double result = number1 * number2;
System.out.println("result:" + result);
output.println(result);
}
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
output.close();
file1.close();
file2.close();
}
}
Edit: Also you may want to modularize your code for instance creating a method that help reduce duplicated code. Also you may be interested to look for NumberFormatException in case any number is not properly formatted or includes letters for example.
private double readDoubleFromFile(BufferedReader file) throws IOException {
String numberAsString = file.readLine();
if (numberAsString == null) {
throw new IOException();
}
double number = Double.parseDouble(numberAsString);
return number;
}
The DataInputStream class is not for reading text files. it can only be used to read what DataOutput writes. If you have rows of human-readable numbers, you need to use an InputStreamReader and then parse the resulting streams with things like Double.parseDouble
Maybe you want to use a BufferedReader for this.
BufferedReader in = new BufferedReader(
new FileReader(args[0]));
Then:
String num = null;
while((num = in.readLine()) != null){
double d = Double.parseDouble(num);
//now you have a double value
}
This way you do not depend on the exception to indicate the end of file.
You need to call output.flush just before closing the stream. Also, you should close the streams to the files in a finally block, this will make sure that the close command wil always be executed.
The DataInputStream class reads from a binary file (or other source such as socket). This means that it is going to be completely misinterpreting those input text files, with possibly amusing (or very irritating) results. To read numbers from a text file, you should use a BufferedReader wrapping an InputStreamReader to read lines and then convert those to numbers with suitable parsing methods (e.g., Double.parseDouble if you're wanting to produce a floating-point number).
When testing these things, it's often helpful to put in some debugging output inside the loop that prints out each value as you read it. Like that, you can see if things have got stuck in some unexpected way.
With this while (true) without a break your code is basically running in an infinite loop and never stopping unless there's an exception.
If it did terminate but you didn't see an exception, then it might be caused by calling System.exit(1) in the catch. It might be too late then to print "Error" anyway (the stdout might have been abrupted too early) and the file will never be flushed/closed. Remove that System.exit(1) line.
Also, closing is supposed to happen in finally block. And best is to not print some nothing-saying message on exception but just let them go. Since you already have a throws Exception on the method, just remove the entire catch. Only use it when you can handle exceptions in a sensible manner.
PrintWriter output = new PrintWriter("output2.txt");
try {
output.println("something");
} finally {
output.close();
}
After
output.println(result);
add
output.flush();

Categories