Problems with reading a file in java - java

I'm doing a project for a class, but for the life of me I'm having the hardest time figuring out how to read text from a file. We have to create a traffic light that queues trucks and cars coming from North, South, East, and West. It's been a long time since I've done any coding, so I'm struggling immensely. I think it just reads the memory location. Here's my code for reading in a file.
package Project1;
import java.io.*;
import java.util.*;
public class TrafficSim {
public String input;
public TrafficSim(String input)
{
this.input = input;
readFromFile();
}
private boolean readFromFile()
{
File inputText = new File("input1.txt");
try
{
Scanner scan = new Scanner(inputText);
while(scan.hasNextLine())
{
String direction = scan.nextLine();
int num = scan.nextInt();
}
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
return false;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
TrafficSim sim = new TrafficSim("input1.txt");
System.out.println(sim);
}
}

Your method readFromFile sure enough reads from a file, but then it doesn't do anything. All you do is read line by line, storing a line of text and an int in variables which are forgotten after each iteration of your while loop.
Your code System.out.println(sim) prints out whatever the toString method of your class returns, and since you didn't override that method it will print out the result of Object.toString, which is not what you want.
To put it simply, you're reading from a file but you're not doing anything with the contents that you read.

Here is what I would do....
public class TrafficSim {
private String input;
private String content;
public TrafficSim(String input) {
this.setInput(input);
this.setContent(readFromFile());
}
private String readFromFile() {
File inputText = new File(input);
StringBuilder sb = new StringBuilder();
try {
Scanner scan = new Scanner(inputText);
while (scan.hasNextLine()) {
sb.append(scan.nextLine());
}
scan.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return sb.toString();
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getInput() {
return input;
}
public void setInput(String input) {
this.input = input;
}
public static void main(String[] args) {
TrafficSim sim = new TrafficSim("input1.txt");
System.out.println(sim.getContent());
}
}
The issue I see though is that you're not following the comments and suggestions already made. ktm5124 was pretty clear on what the problem is. At some point you're going to have to understand what is going on here and how to fix it.

Related

How do you create objects of another class from a .csv file?

Im working on a task that requires me to read from a .csv file using stream API, go over each line and construct an object with the lines. The object class is called Planet and is:
public Planet(String name, long inhabitants, boolean stargateAvailable, boolean dhdAvailable, List<String> teamsVisited) {
}
public String getName() {
return name;
}
public long getInhabitants() {
return inhabitants;
}
public boolean isStargateAvailable() {
return stargateAvailable;
}
public boolean isDhdAvailable() {
return dhdAvailable;
}
public List<String> getTeamsVisited() {
return teamsVisited;
}
#Override
public String toString() {
return name;
}
}
So using stream API to go over each of the lines of the .cvs file i need to create objects of class Planet.
I havent made any progress at all because I really am not sure how to use stream API
public class Space {
public List<Planet> csvDataToPlanets(String filePath) {
return null;
}
try the below snippet.
File inputF = new File(inputFilePath);
InputStream inputFS = new FileInputStream(inputF);
BufferedReader br = new BufferedReader(new InputStreamReader(inputFS));
// skip the header of the csv
inputList = br.lines().skip(1).map(mapToItem).collect(Collectors.toList());
br.close();
For more information check this link
public static void main(String args[]) {
String fileName = "<Your File Path"";
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.forEach(<Method to split the string based with ',' as delimiter and call Constructor using Reflection API>);
} catch (IOException e) {
e.printStackTrace();
}
}

Creating a void method that reads a file, that can be called by other methods in the class?

public class Dash {
public void readFile(String fil) throws FileNotFoundException {
try {
Scanner input = new Scanner(new File(fil));
String text = input.next();
input.close();
} catch (FileNotFoundException e) {
}
}
public int getNumDashes() throws FileNotFoundException {
readFile(fil);
String text = input.next();
// code to find number of dashes from the string of the read file.
}
}
As indicated in the title, I would like to read the file in one method. Since I cannot return a string from readFile method, I would have to obtain the string from within the getNumDashes method. However, I'm not sure how to do this. I would like my second method's return value to be based of off whatever file name is passed into readFile().
You could use a non-static field for your string, where you store your text from the input file.
public class Dash {
String text;
public void readFile(String fil) throws FileNotFoundException {
try{
Scanner input = new Scanner (new File(fil));
text= input.next();
input.close();
}
catch (FileNotFoundException e){
}
public int getNumDashes() throws FileNotFoundException {
readFile(fil);
// You can read from the field *text* here and process the input
// code to find number of dashes from the string of the read file.
}
}

Java parse csv class

I am making a class in java to parse in CSV's. It will read in the file line by line and parse out each field according to the regex pattern into an array, and then print that array. I put all this together in a main driver below. I looked over everything and it seems to be functional but for some reason whenever I run it, it just gets stuck in an infinite loop and will not cease. I have looked over this many times and can just not find where this would happen. Any help with this issue would be greatly appreciated!
import java.io.FileInputStream;
import java.io.IOException;
import java.util.regex.Pattern;
/**
*
*/
public class Csv {
private FileInputStream fin;
private String line;
private String[] parsedFields;
public boolean isEOL(char n) {
boolean eol;
if (n == '\n' || n == '\r') {
eol = true;
}
else
eol=false;
return eol;
}
public String getLine()
{
try
{
char c;
c= (char) fin.read();
while(!isEOL(c))
{
line+=c;
}
}
catch (IOException e) {
System.out.println("Input Error.");
}
return line;
}
public void parseFields(String s)
{
Pattern CSVLine=Pattern.compile("\"([^\"]*)\"|(?<=,|^)([^,]*)(?:,|$)");
parsedFields=CSVLine.split(s);
}
public void execute()
{
String field=getLine();
parseFields(field);
}
public void setFin(FileInputStream usrFin)
{
fin=usrFin;
}
public void outputFields()
{
for(int i=0; i<parsedFields.length;i++)
{
System.out.println(parsedFields[i]);
}
}
public static void main(String args[])
{
try {
FileInputStream fis;
fis = new FileInputStream("test.txt");
Csv test= new Csv();
test.setFin(fis);
test.execute();
test.outputFields();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
c= (char) fin.read();
while(!isEOL(c))
{
line+=c;
}
In this part, you loop, adding c, but you never read again. c never changes during the loop, and probably is stuck there. You need to have the c = fin.read(); inside the loop too.
public static List<String> readLine(String filePath){
List<String> listStr = new ArrayList<String>();
try {
BufferedReader br = new BufferedReader(new FileReader(filePath));
String line = null;
Pattern pat = Pattern.compile(LINE_PATTERN_REGEXP);
while((line=br.readLine())!=null){
Matcher matcher = pat.matcher(line);
if(!matcher.find()){
listStr.add(line);
}
}
br.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
return listStr;
}
}

How to use ArrayList while adding something to another Class's constructor ?

I'm try to create one simple reservation system, we'll read a file, then we'll add Train, Bus, etc., then we'll writer everything to output.
import java.io.*;
import java.util.*;
public class Company
{
private static ArrayList<Bus> bus = new ArrayList<Bus>();
static int buscount = 0, traincount = 0;
public static void main (String[] args) throws IOException
{
FileParser();
}
public Company()
{
}
public static void FileParser()
{
try {
File file = new File(); //i fill this later
File file2 = new File(); // i fill this later
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(file2);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
String line;
while ((line = br.readLine()) != null)
{
String[] splitted = line.split(",");
if(splitted[0].equals("ADDBUS"))
{
bus.add(buscount) = Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]);
}
}
}
catch (FileNotFoundException fnfe) {
}
catch (IOException ioe) {
}
}
}
I try to read the file line by line. For example one of the line is "ADDBUS,78KL311,10,140,54" I split the line for "," then i try to add every pieces of array to Bus' class' constructor but i couldn't figured it out.
My Bus Class is like `
public class Bus extends Vehicle{
private String command;
private String busName;
private String busPlate;
private String busAge;
private String busSpeed;
private String busSeat;
public Bus(String command, String busname, String busplate, String busage, String busspeed, String busseat)
{
this.command = command;
this.busName = busname;
this.busPlate = busplate;
this.busAge = busage;
this.busSpeed = busspeed;
this.busSeat = busseat;
}
public String getBusName() {
return busName;
}
public void setBusName(String busName) {
this.busName = busName;
}
public String getBusPlate() {
return busPlate;
}
public void setBusPlate(String busPlate) {
this.busPlate = busPlate;
}
public String getBusAge() {
return busAge;
}
public void setBusAge(String busAge) {
this.busAge = busAge;
}
public String getBusSpeed() {
return busSpeed;
}
public void setBusSpeed(String busSpeed) {
this.busSpeed = busSpeed;
}
public String getBusSeat() {
return busSeat;
}
public void setBusSeat(String busSeat) {
this.busSeat = busSeat;
}
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
}
can someone show me a way to solve this problem?
Thank you,
You are missing the keyword new to create a new instance of the class:
bus.add(new Bus(...));
You can add items to ArrayList like this
bus.add( new Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]));
you were missing new keyword before Bus constructor call. Then you can increment the counter (or do whatever)
bus.add( new Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]));
buscount++;
try to add new Bus(...)
bus.add( new
Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]));
As I understand if you want to call constructor you need to call new Bus(parms).
when you say new it will call constructor of your class
when you say this() again it going to call enclosing class' constructor
if you say super() it will call super class' constructor.
if you want it into a map order by counter you can use this:
Map(Integer, Bus) busPosition = new HashMap<>();
busPosition.put(buscount, new
Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]));

Using multiple classes getting Null pointer exception. Probably syntactical.

So I am supposed to make 3 classes and am given a 4th class to use for a user interface. One class (DBBinding) is supposed to have a String key and String value and take something like name:Alien or star: harry dean and make name or star be the "key" and the other is the "value" the next class (DBrecord) is to hold a group of these "bindings" as one record. I have chosen to keep a group of these bindings in a ArrayList. The third class(DBTable) is another ArrayList but of . I am at the point where I am reading in a line of txt from file where each line of txt is going to be one DBrecord that we know will be in correct formatting(key:value, key:value, key:value, and so on).
Where I am having trouble is within the DBrecord class. I have a method(private void addBindingToRecord(String key_, String value_)) that is called from (public static DBrecord createDBrecord(String record)) from within the DBrecord class here are each methods code.
I am having trouble with the addBindingToRecord method ... it null pointer exceptions on the first time used. I think it has to do with sytax and how I am calling the "this.myDBrecord.add(myDBBinding);"... have tried it multiple ways with same result....
public static DBrecord createDBrecord(String record)//takes a string and breaks it into DBBindings and makes a record with it.
{
DBrecord myRecord=new DBrecord();
String temp[];
temp=record.split(",",0);
if(temp!=null)
{
for(int i=0; i<Array.getLength(temp); i++)
{
System.out.println("HERE");//for testing
String temp2[];
temp2=temp[i].split(":",0);
myRecord.addBindingToRecord(temp2[0], temp2[1]);
}
}
return myRecord;
}
private void addBindingToRecord(String key_, String value_)
{
DBBinding myDBBinding=new DBBinding(key_, value_);
if(myDBBinding!=null)//////////////ADDED
this.myDBrecord.add(myDBBinding);///Here is where my null pointer exception is.
}
I am going to post the full code of all my classes here so you have it if need to look at. Thank for any help, hints, ideas.
package DataBase;
import java.io.*;
public class CommandLineInterface {
public static void main(String[] args) {
DBTable db = new DBTable(); // DBTable to use for everything
try {
// Create reader for typed input on console
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line;
while (true) {
int length = 0;
int selectedLength = 0;
// YOUR CODE HERE
System.out.println("\n" + length + " records (" + selectedLength + " selected)");
System.out.println("r read, p print, sa select and, so select or, da ds du delete, c clear sel");
System.out.print("db:");
line = reader.readLine().toLowerCase();
if (line.equals("r")) {
System.out.println("read");
String fname;
System.out.print("Filename:");
//fname = reader.readLine();////ADD BACK IN AFTER READ DEBUGED
// YOUR CODE HERE
fname="movie.txt";
db.readFromFile(fname);
}
else if (line.equals("p")) {
System.out.println("print");
// YOUR CODE HERE
DBTable.print();
}
else if (line.equals("da")) {
System.out.println("delete all");
// YOUR CODE HERE
}
else if (line.equals("ds")) {
System.out.println("delete selected");
// YOUR CODE HERE
}
else if (line.equals("du")) {
System.out.println("delete unselected");
// YOUR CODE HERE
}
else if (line.equals("c")) {
System.out.println("clear selection");
/// YOUR CODE HERE
}
else if (line.equals("so") || line.equals("sa")) {
if (line.equals("so")) System.out.println("select or");
else System.out.println("select and");
System.out.print("Criteria record:");
String text = reader.readLine(); // get text line from user
// YOUR CODE HERE
}
else if (line.equals("q") || line.equals("quit")) {
System.out.println("quit");
break;
}
else {
System.out.println("sorry, don't know that command");
}
}
}
catch (IOException e) {
System.err.println(e);
}
}
}
package DataBase;
import java.util.*;
import java.io.*;
public class DBTable {
static ArrayList<DBrecord> myDBTable;
public DBTable()
{
ArrayList<DBrecord> myDBTable= new ArrayList<DBrecord>();
}
public static void addRecordToTable(DBrecord myRecord)//added static when added addRecordToTable in readFromFile
{
if(myRecord!=null)
{myDBTable.add(myRecord);}
}
public static void readFromFile(String FileName)
{
try
{
FileReader myFileReader=new FileReader(FileName);
String line="Start";
BufferedReader myBufferdReader=new BufferedReader(myFileReader);
while(line!="\0")
{
line=myBufferdReader.readLine();
if(line!="\0")
{
System.out.println(line);//TEST CODE
addRecordToTable(DBrecord.createDBrecord(line));// made addRecordToTable static.
}
}
}catch(IOException e)
{System.out.println("File Not Found");}
}
public static void print()
{
if (myDBTable==null)
{
System.out.println("EMPTY TABLE");
return;
}
else
{
for (int i=0; i<myDBTable.size(); i++)
{
System.out.println(myDBTable.get(i).toString());
}
}
}
}
package DataBase;
import java.util.*;
import java.lang.reflect.Array;
//import DataBase.*;//did not help ... ?
public class DBrecord {
boolean select;
String key;
//need some type of collection to keep bindings.
ArrayList<DBBinding> myDBrecord;
public DBrecord()
{
//DBrecord myRecord=new DBrecord();
select=false;
ArrayList<DBBinding> myDbrecord=new ArrayList<DBBinding>();
}
private void addBindingToRecord(String key_, String value_)
{
DBBinding myDBBinding=new DBBinding(key_, value_);
//System.out.println(myDBBinding.toString());//for testing
if(myDBBinding!=null)//////////////ADDED
this.myDBrecord.add(myDBBinding);
System.out.println(key_);//for testing
System.out.println(value_);//for testing
}
public String toString()
{
//out put key first then all values in collection/group/record. use correct formatting.
StringBuilder myStringbuilder=new StringBuilder();
for (int i=0;i<this.myDBrecord.size();i++)
{
myStringbuilder.append(myDBrecord.get(i).toString());
myStringbuilder.append(", ");
}
myStringbuilder.delete(myStringbuilder.length()-2, myStringbuilder.length()-1);//delete last ", " thats extra
return myStringbuilder.toString();
}
public static DBrecord createDBrecord(String record)//takes a string and breaks it into DBBindings and makes a record with it.
{
//System.out.println("HERE");//for testing
DBrecord myRecord=new DBrecord();
String temp[];
temp=record.split(",",0);
if(temp!=null)
{
//System.out.println("HERE");//for testing
//for(int i=0; i<Array.getLength(temp); i++) ///for testing
//{System.out.println(temp[i]);}
for(int i=0; i<Array.getLength(temp); i++)
{
System.out.println("HERE");//for testing
String temp2[];
temp2=temp[i].split(":",0);
System.out.println(temp2[0]);//for testing
System.out.println(temp2[1]);//for testing
myRecord.addBindingToRecord(temp2[0], temp2[1]);
System.out.println(temp2[0]+ " "+ temp2[1]);////test code
}
}
return myRecord;
}
}
package DataBase;
public class DBBinding {
private String key;
private String value;
public DBBinding(String key_, String value_)
{
key =key_;
value=value_;
}
public String getKey()
{return key;}
public String getValue()
{return value;}
public String toString()
{return key+": "+value;}
}
In your constructor: ArrayList<DBBinding> myDbrecord=new ArrayList<DBBinding>();
You only create a local variable named myDbrecord and initialize it, instead of initializing the field myDBrecord.
You probably wanted instead:
myDBrecord = new ArrayList<DBBinding>();

Categories

Resources