Infinite Loop when looping through FileInputStream - java

Alright, so I am writing a Java application to import a csv file and then loop through the results, and load them into an array. I am importing the file correctly because it doesn't through an Exception. My issues is that when I try to count the number of records in the FileInputStream I am trapped in an infinite loop. What could be the issue here. Heres the code:
This is my class with a Main method which calls go():
public void go() {
pop = new PopularNames();
popGui = new PopularNamesGui();
String file = popGui.userInput("Enter the correct name of a file:");
pop.setInputStream(file);
pop.getNumberOfNames();
}
This is the class PopularNames (pop), and in the below method I am setting the inputStream var to a new FileINputStream. The file name is provided by the user.
public void setInputStream(String aInputStream) {
try {
inputStream = new Scanner(new FileInputStream(aInputStream));
} catch (FileNotFoundException e) {
System.out.println("The file was not found.");
System.exit(0);
}
}
This is the trouble method. Where I am simply looping through the FileInputStream and counting the number of records:
public void getNumberOfNames() {
while (this.inputStream.hasNext()) {
fileDataRows++;
}
}

public void getNumberOfNames() {
while (this.inputStream.hasNext()) {
inputStream.nextLine(); // Need to read it so that we can go to next line if any
fileDataRows++;
}
}

Related

How to split Set<E>?

I have class Laptops. Inside this class I have 3 parameters "String name, Integer screen, Integer price" I created Set and now I need to split it and compare with price if price over 2000$ write to file if lower write to second file.
This is my method:
public void check(Set<Laptops> laptops, File under2000, File over2000){
try{
String under2000 = "2000";
OutputStream under = new FileOutputStream(under2000);
PrintStream printStream = new PrintStream(under);
Iterator<Laptops> lap = laptops.iterator();
while (lap.hasNext()){
lap.next();
if (laptops.contains(under2000)) {
printStream.print(lap);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Can someone help me?
It is easy to split the set with streams:
Set<Laptops> over2000 = laptops.stream().filter(l -> l.getPrice() > 2000).collect(Collectors.toSet());
Set<Laptops> rest = new HashSet<>(laptops);
rest.removeAll(over2000);
The first part filters all laptops with price over 2000. The rest takes the original set and removes those laptops. Than you can handle each set as you like.
public void check(Set<Laptops> laptops, File under2000file, File over2000file){
try {
PrintStream under2000 = new PrintStream(under2000file);
PrintStream over2000 = new PrintStream(over2000file);
for(Laptop laptop: laptops) {
if(laptop.getPrice() < 2000) {
under2000.println(laptop);
} else {
over2000.println(laptop);
}
}
under2000.close();
over2000.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

How to overwrite a file that is altering an arraylist

I'm writing a program in order to keep track of DVDs in my library. I'm having trouble altering the text file that saves an added or removed DVD object from the arraylist. Whenever I call my save method, which is the one that overwrites the existing text file holding all the information, it will not change it whatsoever. My add and remove methods work fine but it's just the save method which overwrites the file that I'm reading from that will not work. The following code is what I was attempting to use to save the arraylist to the file. My filename is DVDCollection.txt and the boolean variable flag is a static variable used to check whether or not the code which adds or removes an object from the arraylist was reached.
public void save() {
try{
if(flag=true){
FileWriter instream = new FileWriter("DVDCollection.txt",false);
instream.close();
}else{
return;
}
}catch(IOException e){
System.out.println("The file could not be written to!");
}
}
If you are using java 8 or above it's as simple as:
List<String> lines = Arrays.asList("first line", "second line");
try {
Files.write(Paths.get("my-file.txt"), lines);
} catch (IOException e) {
//handle exception
}
Make sure you provide the right path!
Not sure, why this method should save an array list, as the actual code that writes to this file is missing. Here is simple test, let's start here:
import java.io.*;
import java.util.*;
public class FileSaveTest {
public static void main(String[] args) {
FileSaveTest test = new FileSaveTest();
test.fill();
test.save();
}
public void fill() {
arrayList.add("My disc 1");
arrayList.add("My disc 2");
arrayList.add("Another disc");
}
public void save() {
try {
if(flag) { // you dont need ==true
FileWriter instream = new FileWriter("DVDCollection.txt",false);
for (String entry : arrayList) {
instream.write(entry + "\n");
}
instream.close();
} else {
return;
}
} catch(IOException e) {
System.out.println("The file could not be written to!");
}
}
private ArrayList<String> arrayList = new ArrayList<>();
private static boolean flag = true;
}
Next, it's not very good, to close the file in such manner. If an exception occurs while writing, the file will not be closed. instream.close() should be put into the "finally" block. This block will be executed in any case, regardless of whether an exception occurred or the return keyword met:
public void save() {
Writer instream = null;
try {
if(flag) { // you dont need ==true
instream = new FileWriter("DVDCollection.txt",false);
for (String entry : arrayList) {
instream.write(entry + "\n");
}
} else {
return;
}
} catch(IOException e) {
System.out.println("The file could not be written to!");
} finally {
try {
if (instream != null)
instream.close();
} catch (IOException e) {
System.err.println("Exception during close");
}
}
}
Or, if you are using java 7, you can use try-with-resources syntax:
public void save() {
if(flag) { // you dont need ==true
try (Writer instream = new FileWriter("DVDCollection.txt",false)) {
for (String entry : arrayList)
instream.write(entry + "\n");
} catch(IOException e) {
System.out.println("The file could not be written to!");
}
} // you dont need "return else { return; }" anymore
}

How to get array.length after it has been deserialized [duplicate]

This question already has answers here:
why does the catch block give an error with variable not initialized in Java
(7 answers)
Closed 6 years ago.
So, I'm working on a project that automates everything from character sheets to dice rolls for a table top RPG I like to play. I'm trying to store character data (character name, 2 arrays of stats, and 2 arrays of those stat values) that can be accessed at the start of executing the app. This has been very helpful so far.
However, I'd also like to display the name and stats so the user can confirm that this is the character data they want to use. And I'm having trouble displaying the data in a readable format. Here's my code (you'll find the problem I'm having toward the bottom, although if you see anything else that could be optimized along the way, I would appreciate any feedback :-)":
import java.io.*;
import javax.swing.JOptionPane;
public class fengShuiFiles implements Serializable {//start class
private FileOutputStream outFile;
private ObjectOutput objectWriter;
private FileInputStream inFile;
private ObjectInputStream objectReader;
public void WriteFile(String fileNameIn, String[] sArray1, String[] sArray2,
String[] sArray3, String[] sArray4) {
try {
outFile = new FileOutputStream(fileNameIn + ".txt", true);
objectWriter = new ObjectOutputStream(outFile);
objectWriter.writeObject(sArray1);
objectWriter.writeObject(sArray2);
objectWriter.writeObject(sArray3);
objectWriter.writeObject(sArray4);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "I/O occurred during a write operation\nFor more",
"information see console output.",
"Read File", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
} // End try/catch
} // End Open
//not sure if I'll need this. Keeping it for now just in case
//public void writeRecords(String textRecords)
//{
// outFile.close();
// pw.println(textRecords);
//} // End WriteRecords
public void ReadFile(String fileNamein) throws FileNotFoundException {
fengShuiFiles[] sArray1, sArray2, sArray3, sArray4;
try {
inFile = new FileInputStream(fileNamein + ".txt");
objectReader = new ObjectInputStream(inFile);
sArray1 = (fengShuiFiles[]) objectReader.readObject();
sArray2 = (fengShuiFiles[]) objectReader.readObject();
sArray3 = (fengShuiFiles[]) objectReader.readObject();
sArray4 = (fengShuiFiles[]) objectReader.readObject();
} catch (IOException | ClassNotFoundException e) {
JOptionPane.showMessageDialog(null, "I/O error occurred opening a",
"file\nFor more information see console output.",
"Read File", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
} // End try/catch
for (int x = 0; x < sArray1.length; x++) {
}
}
public void closeFile() {
try {
outFile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} // End closeFile
}//end class
So, that sArray1.length in the for statement toward the bottom? It's coming up with an error message saying that sArray1 may not have been initialized. And I'm having trouble figuring out why, and how I can get that length so I can print out the arrays in a readable manner. Does anyone have any ideas? Thanks.
You need to initialize local variables. If an exception occurs, it's possible that some or all of the arrays aren't initialized and the compiler won't allow that.
The easiest way to get rid of the error is to initialize the arrays to null, but your program has a logic problem. You're catching the exceptions and continuing, even though there's no way your program can work correctly after that. You should instead throw the exceptions out of the readFile() method and then most likely exit the program. You could also continue as if the file didn't exist, but at least show a warning about it.
You always have to initialize variables in java. You do this in your try block, but if an exception occurs, the array will not have been initialized.
You can move the for loop to the try block:
public void ReadFile(String fileNamein) throws FileNotFoundException {
fengShuiFiles[] sArray1, sArray2, sArray3, sArray4;
try {
...
for(int x = 0; x < sArray1.length; x++) {
}
} catch (IOException | ClassNotFoundException e) {
...
} // End try/catch
}
Or use a default value to initialize the array in the catch block:
public void ReadFile(String fileNamein) throws FileNotFoundException {
fengShuiFiles[] sArray1, sArray2, sArray3, sArray4;
try {
...
} catch (IOException | ClassNotFoundException e) {
...
sArray1 = new fengShuiFiles[0]; // Some default value.
} // End try/catch
for(int x = 0; x < sArray1.length; x++) {
}
}
Something that might be more convenient though, is to return the read arrays, and do something with them in the calling method.
For instance:
public Optional<fengShuiFiles[][]> ReadFile(String fileNamein) throws FileNotFoundException {
try {
fengShuiFiles[] sArray1, sArray2, sArray3, sArray4;
// read the file
return Optional.of(new fenShuiFiles[][]{ sArray1, sArray2, sArray3, sArray4 });
} catch (IOException | ClassNotFoundException e) {
...
return OPtional.empty();
}
}
Then in some other method:
Optional<fengShuiFiles[][]> ret = ReadFile(...);
if(ret.isPresent()) {
for(fengShuiFiles[] arr : ret.get()) {
System.out.println(Arrays.toString(arr)); // Print here
}
}

How to use a Path object as a String

I'm looking to try and create a Java trivia application that reads the trivia from separate question files in a given folder. My idea was to use the run() method in the FileHandler class to set every text file in the folder into a dictionary and give them integer keys so that I could easily randomize the order at which they appear in the game. I found a simple chunk of code that is able to step through the folder and get the paths of every single file, but in the form a Path class. I need the paths (or just the names) in the form a String class. Because I need to later turn them into a file class (which excepts a String Constructor, not a Path). Here is the chunk of code that walks through the folder:
public class FileHandler implements Runnable{
static Map<Integer, Path> TriviaFiles; //idealy Map<Integer, String>
private int keyChoices = 0;
public FileHandler(){
TriviaFiles = new HashMap<Integer, Path>();
}
public void run(){
try {
Files.walk(Paths.get("/home/chris/JavaWorkspace/GameSpace/bin/TriviaQuestions")).forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
TriviaFiles.put(keyChoices, filePath);
keyChoices++;
System.out.println(filePath);
}
});
} catch (FileNotFoundException e) {
System.out.println("File not found for FileHandler");
} catch (IOException e ){
e.printStackTrace();
}
}
public static synchronized Path getNextValue(){
return TriviaFiles.get(2);
}
}
There is another class named TextHandler() which reads the individual txt files and turns them into questions. Here it is:
public class TextHandler {
private String A1, A2, A3, A4, question, answer;
//line = null;
public void determineQuestion(){
readFile("Question2.txt" /* in file que*/);
WindowComp.setQuestion(question);
WindowComp.setAnswers(A1,A2,A3,A4);
}
public void readFile(String toRead){
try{
File file = new File("/home/chris/JavaWorkspace/GameSpace/bin/TriviaQuestions",toRead);
System.out.println(file.getCanonicalPath());
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
question = br.readLine();
A1 = br.readLine();
A2 = br.readLine();
A3 = br.readLine();
A4 = br.readLine();
answer = br.readLine();
br.close();
}
catch(FileNotFoundException e){
System.out.println("file not found");
}
catch(IOException e){
System.out.println("error reading file");
}
}
}
There is stuff I didn't include in this TextHandler sample which is unimportant.
My idea was to use the determineQuestion() method to readFile(FileHandler.getNextQuestion).
I am just having trouble working around the Path to String discrepancy
Thanks a bunch.
You can simply use Path.toString() which returns full path as a String. But kindly note that if path is null this method can cause NullPointerException. To avoid this exception you can use String#valueOf instead.
public class Test {
public static void main(String[] args) throws NoSuchFieldException, SecurityException {
Path path = Paths.get("/my/test/folder/", "text.txt");
String str = path.toString();
// String str = String.valueOf(path); //This is Null Safe
System.out.println(str);
}
}
Output
\my\test\folder\text.txt

Error Reading and writing files (Java) [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Hi guys i just implemented object files into my program and i am constantly getting the errors (error reading file and problem writing to file) these are 2 errors in my try catch block, when i try to read the file it does not load, saving doesn't work either.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
public class Stores implements Serializable
{
public static ArrayList<Student> stud1 = new ArrayList<Student>();
public static ArrayList<SubjectTeacher> sTeach1 = new ArrayList<SubjectTeacher>();
private static int iT = 0;
private static int iS = 0;
public static void savet (ArrayList<SubjectTeacher> teachIn, int count)
{
iT = count;
sTeach1 = teachIn;
saveTeachToFile();
}
public static void saves (ArrayList<Student> studIn, int count)
{
iS = count;
stud1 = studIn;
saveStudToFile();
}
public static ArrayList<Student> getStud ()
{
return stud1;
}
public static ArrayList<SubjectTeacher> getTeach ()
{
return sTeach1;
}
public static int getStudSize()
{
return stud1.size();
}
public static int getTeachSize()
{
return sTeach1.size();
}
private static void saveStudToFile()
{
try
{
// create a FileOutputStream object which will handles the writing of the sudent list of objects to the file.
FileOutputStream studentFile = new FileOutputStream("Students.obf");
// the OutputObjectStream object will allow us to write whole objects to and from files
ObjectOutputStream studentStream = new ObjectOutputStream(studentFile);
for(Student item: stud1) // enhanced for loop
// Loop through the list of studentsListIn and for each of these objects, wite them to the file
{
studentStream.writeObject(item);
}
//close the file so that it is no longer accessible to the program
studentStream.close();
}
catch(IOException e)
{
System.out.println("There was a problem writing the File");
}
}
private static void saveTeachToFile()
{
try
{
FileOutputStream teacherFile = new FileOutputStream("Teacher.obf");
ObjectOutputStream teacherStream = new ObjectOutputStream(teacherFile);
for(SubjectTeacher item1: sTeach1) // enhanced for loop
{
teacherStream.writeObject(item1);
}
//close the file so that it is no longer accessible to the program
teacherStream.close();
}
catch(IOException e)
{
System.out.println("There was a problem writing the File");
}
}
public static void loadStudentList()
{
boolean endOfFile = false;
Student tempStudent;
try
{
// create a FileInputStream object, studentFile
FileInputStream studentFile = new FileInputStream("Students.obf");
// create am ObjectImnputStream object to wrap around studentStream
ObjectInputStream studentStream = new ObjectInputStream(studentFile) ;
// read the first (whole) object with the readObject method
tempStudent = (Student) studentStream.readObject();
while (endOfFile != true)
{
try
{
stud1.add(tempStudent);
// read the next (whole) object
tempStudent = (Student) studentStream.readObject();
}
//use the fact that the readObject throws an EOFException to check whether the end of eth file has been reached
catch(EOFException e)
{
endOfFile = true;
}
studentStream.close();
}
}
catch(FileNotFoundException e)
{
System.out.println("File not found");
}
catch(ClassNotFoundException e) // thrown by readObject
/* which indicates that the object just read does not correspond to any class
known to the program */
{
System.out.println("Trying to read an object of an unkonown class");
}
catch(StreamCorruptedException e) //thrown by constructor
// which indicates that the input stream given to it was not produced by an ObjectOutputStream object {
{
System.out.println("Unreadable File Format");
}
catch(IOException e)
{
System.out.println("There was a problem reading the file");
}
}
public static void loadTeacherList()
{
boolean endOfFile = false;
SubjectTeacher tempTeacher;
try
{
FileInputStream teacherFile = new FileInputStream("Teacher.obf");
ObjectInputStream teacherStream = new ObjectInputStream(teacherFile) ;
tempTeacher = (SubjectTeacher) teacherStream.readObject();
while (endOfFile != true)
{
try
{
sTeach1.add(tempTeacher);
// read the next (whole) object
tempTeacher = (SubjectTeacher) teacherStream.readObject();
}
//use the fact that the readObject throws an EOFException to check whether the end of eth file has been reached
catch(EOFException e)
{
endOfFile = true;
}
teacherStream.close();
}
}
catch(FileNotFoundException e)
{
System.out.println("File not found");
}
catch(ClassNotFoundException e) // thrown by readObject
/* which indicates that the object just read does not correspond to any class
known to the program */
{
System.out.println("Trying to read an object of an unkonown class");
}
catch(StreamCorruptedException e) //thrown by constructor
// which indicates that the input stream given to it was not produced by an ObjectOutputStream object {
{
System.out.println("Unreadable File Format");
}
catch(IOException e)
{
System.out.println("There was a problem reading the file");
}
}
}
Well, for one thing, you should edit the question with the correct code so it doesn't get closed. Second, A couple of things could be happening.
The classes you're writing to file aren't serializable
The files are readonly or write protected somehow
Based on the code from your updated question, it looks like you may be confusing which classes need to implement Serializable. The classes that need to implement that are the ones you're actually writing to file (ie SubjectTeacher, etc.).
Check those two, and let me know what you find.
Also, I'd suggest stepping the code and seeing what the exceptions look like at runtime. You'll get a much better idea of what's going on.

Categories