Initialize array of objects from text files - java

I have a program where I need to store users information, and add users. To make it persistent, the program reads all the users data and initializes an array of users upon launch, then saves the information before it closes. Here's my user class:
class User {
String name;
int val = -1;
int oldVal = -1;
public User(String n){
try{
BufferedReader dataReader = new BufferedReader(new FileReader("/Users/" + n));
name = dataReader.readLine();
val = Integer.parseInt(dataReader.readLine());
oldVal = Integer.parseInt(dataReader.readLine());
} catch (Exception e){}
}
This class reads from files in /users, following the format name.txt
John
90
100
My core class looks like this:
import java.io.BufferedReader;
import java.io.FileReader;
class Core{
public static void main (String[] args){
int numUsers = -1;
BufferedReader nameReader = null;
User[] users = null;
try {
nameReader = new BufferedReader(new FileReader("Users/users.txt"));
numUsers = Integer.parseInt(nameReader.readLine());
users = new User[numUsers];
for (int i = 0; i < numUsers; i++){
users[i] = new User(nameReader.readLine());
}
} catch (Exception e) {
System.out.println("Something went wrong. Aborting!");
System.exit(1);
}
for (int i = 0; i < numUsers; i++){
System.out.println("User " + users[i].getName() + "\n Val:" + users[i].getVal() + "\n oldVal: " + users[i].getOldVal());
}
}
}
But running core returns:
User null
val: -1
oldVal: -1
for every user.
What is the problem? Is the system I've made viable, or do I need to change the foundation of my program entirely?
(EDIT to change tags)

Your core is looking for a file in the relative path Users/. Your other class is looking in the absolute path /Users/.
Your textual description says you want /users/ (lower case). On some systems, this will be different again.
I suspect this is causing the problem, or at least part of it.
Looks like what you really want is a relative path, and a .txt on the end:
BufferedReader dataReader = new BufferedReader(new FileReader("Users/" + n + ".txt"));

BufferedReader dataReader = new BufferedReader(new FileReader("/Users/" + n));
Should be
BufferedReader dataReader = new BufferedReader(new FileReader("Users/" + n + ".txt"));
Notice the removal of the extra forward slash and the addition of the .txt extension.

Related

Java Code failing to write to text file,

im trying to run a simulator and there are several problems, primarily....
-the code isn't printing out the values at the end of the program
- the code does not actually create the file
-I'm pretty tired so forgive any foolish mistakes I made or details I have left out.
I've searched the website and I found this
What is the simplest way to write a text file in java
and
how to write to text file outside of netbeans
I thought i could edit code from the first link to work for me, but that did not work( whcih is what you see here)
the second page looks more simple but there's no surrounding code so im not sure what the context is and how I would implement it
import java.util.Random;
import java.util.Scanner;
import java.io.*;
/*
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
*/
public class SimClass {
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in) ;
Random randomNumbers = new Random();
//create object from random class
//create self explanaroty input parameters
int pkt_in_q = 0 ;
int pkt_dropped = 0;
int input ;
int output ;
int buffer ;
int x ;
double y ;
//ask for values for buffer size. input rate, output rate
y = randomNumbers.nextDouble();
//attempt to assign a random number to the variable and
/*here you should get user input.
buffer size, # of repitions , if
*/
//fix this
System.out.print("Enter an integer for the input rate ");
input = keyboard.nextInt();
System.out.print("Enter an integer for the output rate ");
output = keyboard.nextInt();
System.out.print("What is the buffer size ");
buffer = keyboard.nextInt();
for (x = 1000000; x >=0 ; x--)
{ /*
simulate # of packets dropped/in the que,
create file, write results to file, output results,
*/
if (y > input/(output/buffer))
{
if (pkt_in_q < buffer)
{
pkt_in_q++ ;
}
else
{
pkt_dropped++ ;
}
//if statement should terminate here
}
else
if (pkt_in_q > 0)
{
pkt_in_q -- ;
}
}
/*
create file, write results to file, output results,
*/
try { /*this seeems to be the problem, the program is either not doing
anything with this or not making the results visible
*/
String content =( " pkt_in_q is " + pkt_in_q +
"pkt_dropped is " + pkt_dropped);
File file = new File("C:/Temp/inputFile.txt");
// if file doesnt exists, then create it
if (!file.exists())
{
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
try (BufferedWriter bw = new BufferedWriter(fw))
{
bw.write(content);
bw.close();
}
System.out.println("packets dropped value is = " +
pkt_dropped + "packets in q value is = " + pkt_in_q);
}
catch (IOException e)
{
//e.printStackTrace();
}
}
}
I think Code not executing due to file path error.
File file = new File("C:/Temp/inputFile.txt");
There is no folder called "Temp" in the C: drive. If u create Temp folder manually then the code will execute successfully.
File file = new File("D:/Temp/inputFile.txt");
I have created "Temp" folder in D: drive and code executed successfully.
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Random randomNumbers = new Random();
//create object from random class
//create self explanaroty input parameters
int pkt_in_q = 0;
int pkt_dropped = 0;
int input;
int output;
int buffer;
int x;
double y;
//ask for values for buffer size. input rate, output rate
y = randomNumbers.nextDouble() * 10;
System.out.println("Y++++++" + y);
//attempt to assign a random number to the variable and
/*here you should get user input.
buffer size, # of repitions , if
*/
//fix this
System.out.print("Enter an integer for the input rate ");
input = keyboard.nextInt();
System.out.print("Enter an integer for the output rate ");
output = keyboard.nextInt();
System.out.print("What is the buffer size ");
buffer = keyboard.nextInt();
for (x = 1000000; x >= 0; x--) { /*
simulate # of packets dropped/in the que,
create file, write results to file, output results,
*/
if (y > input / (output / buffer)) {
if (pkt_in_q < buffer) {
pkt_in_q++;
} else {
pkt_dropped++;
}
//if statement should terminate here
} else if (pkt_in_q > 0) {
pkt_in_q--;
}
}
/*
create file, write results to file, output results,
*/
try { /*this seeems to be the problem, the program is either not doing
anything with this or not making the results visible
*/
String content = (" pkt_in_q is " + pkt_in_q + "pkt_dropped is " + pkt_dropped);
String folderPath = "D:" + File.separator + "Temp";
String fileName = folderPath + File.separator + "inputFile.txt";
File folder = new File(folderPath);
File file = new File(fileName);
folder.mkdir();
// if file doesnt exists, then create it
if (!file.exists()) {
//file.mkdir();
file.createNewFile();
System.out.println("File created");
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
try {
bw.write(content);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("packets dropped value is = " + pkt_dropped
+ "packets in q value is = " + pkt_in_q);
} catch (IOException e) {
//e.printStackTrace();
}
}
Corrected the code check this and change the file directory and folder directory according to your requirement.
Correction for details:
First you can't define a try block like below
try (BufferedWriter bw = new BufferedWriter(fw))
It should be defined like
try{
}
catch(IOException e)
{
//do something
}
Modified code for that is like below:
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
try
{
bw.write(content);
bw.close();
}
catch (IOException e)
{
//e.printStackTrace();
}
Second you have to create the directory first post that you can create the file inside the directory. so just modified the code to get the directory created and file created.
String folderPath = "D:" + File.separator + "Temp";
String fileName = folderPath + File.separator + "inputFile.txt";
File folder = new File(folderPath);
File file = new File(fileName);
folder.mkdir();
Hope it clarifies your doubt.

Trying to save a clone of an array in a txt file but returns NULL

I am making an app that keeps username and scores from a game in a txt file. The concept is that when it writes a new username and score to the txt file it should open the .txt file, read it and then make a clone of it adding a new uername and score entry in the txt file.
I am thinking of making this with 2 object arrays. The first is the one that is read in and the new will be the one is writen which will have one more entry.
So if player[i] is readen player[i+1] should be writen with new entry.
I am giving u the code below!
private Player[] myplayer=null;
private Player[] mynewplayer=null;
//open Players.txt
int i;
int n;
String filename="players.txt";
try
{
FileReader fp=new FileReader(filename);
BufferedReader bf=new BufferedReader(fp);
n=Integer.parseInt(bf.readLine());
myplayer=new Player[n];
int x=n+1;
mynewplayer=new Player[x];
for(i=0;i<n;i++)
{
String s=bf.readLine();
String user="",score="";
user=s.substring(0,s.indexOf(","));
s=s.substring(s.indexOf(",")+1);
score=s;
myplayer[i]=new Player(user,Double.parseDouble(score));
for(i=0;i<n;i++)
{
mynewplayer[i]= myplayer[i];
}
mynewplayer[x]=new Player(Username,Double.parseDouble(score));
}
bf.close();
fp.close();
}catch(IOException e)
{
System.out.println("Exception was "+e.getMessage());
}
//----------------------------------WRITE mytxt!-------------
n=myplayer.length;
try
{
filename="players.txt";
FileWriter fp=new FileWriter(filename);
fp.write(""+n+"\n");
for(i=0;i<n+1;i++)
fp.write(""+mynewplayer[i]+"\n");
fp.close();
}catch(IOException e)
{
System.out.println("Exception was "+e.getMessage());
}
//----------------------------------WRITE mytxt!-----------
//Get on Message
String s="";
for(i=0;i<mynewplayer.length;i++)
s=s+mynewplayer[i]+"\n";
JOptionPane.showMessageDialog(null,"Players are \n "+s);
Problem is that when it's written, it returns null for mynewplayer.
I suppose the mynewplayer doesnt really take the entries of the "myplayer" but neither writes the new username.
Compile doesnt show any errors. Just writes NULL to the textfile.
Ask me if u want further info on the code writen!
Thanks in advance!
Here is an edited version of your code, with some improvements and there should be a comment around code that I changed, explaining what I did.
Player[] myPlayer = null; // first word uncapitalized, every
Player[] myNewPlayer = null; // other word begins with a capital
//open Players.txt
int i, n; // combine the variables into 1 line
String filename = "players.txt";
try {
FileReader fp = new FileReader(filename);
BufferedReader bf = new BufferedReader(fp);
n = Integer.parseInt(bf.readLine());
// not needed
//myPlayer = new Player[n];
// NOT NEEDED int x = n + 1;
myNewPlayer = new Player[n + 1];
for (i = 0; i < n; i++) {
String s = bf.readLine();
String user, score; // combine variables, doesnt need to initalize them
String[] items = s.split(","); // Splits the line into array elements on every delimiter -> ,
//user = s.substring(0, s.indexOf(","));
//s = s.substring(s.indexOf(",") + 1);
//score = s;
user = items[0];
score = items[1];
// this line below isnt actually needed
//myPlayer[i] = new Player(user, Double.parseDouble(score));
// Create a new player clone, dont copy the previous one
myNewPlayer[i] = new Player(user, Double.parseDouble(score));
}
// We've read all the variables from the text file, now we create the last one
// Since myNewPlayer is (n+1) size, the range of the array is
// 0 to n
// the last index will be n New Score Variable
myNewPlayer[n] = new Player("Username variable", Double.parseDouble("22"));
bf.close();
fp.close();
} catch (IOException e) {
System.out.println("Exception was " + e.getMessage());
}
//----------------------------------WRITE mytxt!-------------
// This is called a ternary operator
// it is a 1 line if statement
// the format is like so
// booleanLogic ? trueAnswer Execution : falseAnswer Execution;
// if () { true }else { false }
n = myNewPlayer != null ? myNewPlayer.length : 0;
// CHANGED HERE - was using the first array rather than second
// dont need the 1st array
try {
filename = "players.txt";
FileWriter fp = new FileWriter(filename);
// Dont need "" before the items
fp.write(n + "\n");
for (i = 0; i < n; i++) {
fp.write(myNewPlayer[i] + "\n");
}
fp.close();
} catch (IOException e) {
System.out.println("Exception was " + e.getMessage());
}
//----------------------------------WRITE mytxt!-----------
//Get on Message
String s = "";
for (i = 0; i < myNewPlayer.length; i++) {
// s += ""; is like doing s = s + "";
s += myNewPlayer[i] + "\n";
}
JOptionPane.showMessageDialog(null, "Players are \n " + s);
I believe that your problem is this:
for(i=0;i<n;i++)
{
String s=bf.readLine();
String user="",score="";
user=s.substring(0,s.indexOf(","));
s=s.substring(s.indexOf(",")+1);
score=s;
myplayer[i]=new Player(user,Double.parseDouble(score));
for(i=0;i<n;i++)
{
mynewplayer[i]= myplayer[i];
}
mynewplayer[x]=new Player(Username,Double.parseDouble(score));
}
You have nested loops, which is fine, but they use the same counter (the variable i ).
So what is happening is the first line of the file is read, and then added to myplayer[0]. However, instead of just also adding it to mynewplayer[0], you start another loop on i. This loop:
for(i=0;i<n;i++)
{
mynewplayer[i]= myplayer[i];
}
is going to copy the first player into mynewplayer[0]...and then null into every other entry (since myplayer only has the firsdt element filled.
The problem is that after that loop completes, i will equal n, so when you get back to the top of the outer loop, the check $i
Perhaps what you should do is this:
for(i=0;i<n;i++)
{
String s=bf.readLine();
String user="",score="";
user=s.substring(0,s.indexOf(","));
s=s.substring(s.indexOf(",")+1);
score=s;
myplayer[i]=new Player(user,Double.parseDouble(score));
mynewplayer[i]= new Player(user,Double.parseDouble(score));
}
mynewplayer[x]=new Player(<the new username>,Double.parseDouble(<the new score>));

program that uses input file and creates a new one

I'm writing a code that uses an input file called InvetoryReport.txt in a program I am supposed to create that is supposed to take this file, and then multiply two pieces of data within the file and then create a new file with this data. Also at the beginning of the program it is supposed to ask you for the name of the input file. You get three chances then it is to inform you that it cannot find it and will now exit, then stop executing.
My input file is this
Bill 40.95 10
Hammer 1.99 6
Screw 2.88 2
Milk .03 988
(The program is supposed to multiply the two numbers in the column and create a new column with the sum, and then under print another line like this
" Inventory Report
Bill 40.95 10 409.5
Hammer 1.99 6 11.94
Screw 2.88 2 5.76
Milk .03 988 29.64
Total INVENTORY value $ 456.84"
and my program I have so far is this
package textfiles;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.IOException;
public class LookOut{
double total = 0.0;
String getFileName(){
System.out.printIn("Type in file name here.");
try {
int count =1;
FileReader fr = new FileReader("InventoryReport.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
out.println(str + "\n");
}
br.close();
} catch (IOException e) {
if(count == 3) {
System.out.printIn("The program will now stop executing.");
System.exit(0);
count++;
}
}
return str;
}
void updateTotal(double d){
total = total + d;
}
double getLineNumber(int String_line){
String [] invRep = line.split(" ");
Double x = double.parseDouble(invRep[1]);
Double y = double.parseDouble(invRep[2]);
return x * y;
}
void printNewData(String = newData) {
PrintWriter pW = new PrintWriter ("newData");
pw.print(newData);
pw.close;
}
public static void main(String[] args){
String str = ("Get file name");
String str = NewData("InventoryReport/n");
File file = new File(str);
Scanner s = new Scanner(file);
while(s.hasNextLine()) {
String line = s.nextLine();
double data = getLineNumber(line);
update total(data);
NewData += line + " " + data + "/n";
Print NewData(NewData);
}
}
}
I'm getting multiple error codes that I just cant seem to figure out.
try {
int count =1;
FileReader fr = new FileReader("InventoryReport.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
br.close();
} catch (IOException e) {
if(count == 3) {
System.out.printIn("The program will now stop executing.");
System.exit(0);
count++;
}
}
Despite your best intentions you are in fact missing a '}'. Note that you haven't escaped the Try block before the catch. I imagine this is because you confused the closing } for the while statement as the closing } for the try block. Do this instead:
try {
int count =1;
FileReader fr = new FileReader("InventoryReport.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
br.close();
}
}
catch (IOException e) {
if(count == 3) {
System.out.printIn("The program will now stop executing.");
System.exit(0);
count++;
}
}
Also, your indentation is ALL OVER THE PLACE. This should be a lesson to you in why you should format your code properly! It is so easy to miss simple syntax errors like that if you're not formatting properly. It's also hard for others to read your code and figure out what's wrong with it.

How to merge data from two text file

I have two related text files shown for example in data1.txt and data2.txt. I want to merge the two files to create result.txt. Any idea how to go about this?
data1.txt
books, 3
Shelf, 5
groceries,6
books, 1
Shelf, 2
data2.txt
books,2
shelf,3
groceries,1
result.txt
books, 3, 2
Shelf, 5,3
groceries,6,1
books, 1,2
Shelf, 2, 3
this is a example for you.first you need to add values to 2d list from data2 text file.and then when line is null in file2 you can get mapping value relative to it's text from that list .so i have a method which will return back the mapping value for a String .code is little long than i thought .i post only relevant methods here.This is link to complete class file
public void marged(){
try {
BufferedReader br1 = null;
BufferedReader br2 = null;
String line1;
String line2;
ArrayList<ArrayList<String>> arrayList = new ArrayList<>();
br1 = new BufferedReader(new FileReader("C:\\Users\\Madhawa.se\\Desktop\\workingfox\\data1.txt"));
br2 = new BufferedReader(new FileReader("C:\\Users\\Madhawa.se\\Desktop\\workingfox\\data2.txt"));
while ((line1 = br1.readLine()) != null) {
String[] split1 = line1.split(",");
String line1word = split1[0].trim();
String line1val = split1[1].trim();
line2 = br2.readLine();
if (line2 != null) {
String[] split2 = line2.trim().split(",");
String line2word = split2[0].trim();
String line2val = split2[1].trim();
ArrayList<String> list = new ArrayList();
list.add(line2word);
list.add(line2val);
arrayList.add(list);
if (line1word.equalsIgnoreCase(line2word)) {
String ok = line1word + "," + line1val + "," + line2val;
System.out.println(ok);
}
} else {
String ok = line1word + "," + line1val + "," + doesexist(arrayList, line1word);
System.out.println(ok);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
this is the method return mapping value
public String doesexist(ArrayList<ArrayList<String>> arrayList, String s) {
for (int i = 0; i < arrayList.size(); i++) {
String get = arrayList.get(i).get(0);
if (get.trim().equalsIgnoreCase(s.trim())) {
return arrayList.get(i).get(1);
}
}
return "-1";
}
output>>
books,3,2
Shelf,5,3
groceries,6,1
books,1,2
Shelf,2,3
Simply add files into an array of File object then read it using loop.
File []files = new Files[amountOfFiles];
//initialize array elements
for(File f:files)
{
//read each file and store it into string variable
}
//finally write the string variable into result.txt file.
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileNotFoundException;
public class SOQ21
{
public SOQ21()
{
merge();
}
public void merge()
{
try
{
String firstfile = "data1.txt";
FileReader fr1 = new FileReader(firstfile);
BufferedReader bfr1 = new BufferedReader(fr1);
String secondfile = "data2.txt";
FileReader fr2 = new FileReader(secondfile);
BufferedReader bfr2 = new BufferedReader(fr2);
/*
^^^ Right here is how you get the files and accompanying BufferedReaders
to handle them
*/
//next, using the readLine() method from the Java API, read each line
//for the first file
//then, separate by taking the words into an ArrayList and storing the
//numbers as Strings in a String[] of equal length of the ArrayList
//Do the same for the second file
//Then, if the word of ArrayList 1 matches the word of ArrayList 2,
//append the String numbers from String[] 2 to String[] 1
//DONE! :)
}
catch(FileNotFoundException ex)
{
//handle how you want
}
}
public static void main(String[] args)
{
SOQ21 soq = new SOQ21();
}
}
The comments I made should answer most of your questions. Lastly, I would pay special attention to the exceptions, I'm not entirely sure how you wanted to deal with that, but make sure you fill it with SOMETHING!

Scanner cant find my file to read [Java with eclipse]

I'm working on a project that takes in criteria supplied by a user, and compares it to an already created list of object containing similar criteria.
Currently, I'm trying to get the program to read the file, but I keep getting my exception and not what I want. My code for the scanner and file is as followed:
package project205;
import java.util.*;
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class HouseList {
ArrayList<House> houseList = new ArrayList<House>();
public HouseList(String fileName)
{
//Open the data file
Scanner myFileIn = null;
try
{
myFileIn = new Scanner(new File("houses.txt"));
}
catch (FileNotFoundException e)
{
System.out.println("File: " + "houses.txt" + " is not found");
}
// First piece of data is the number of records
int numRecords = myFileIn.nextInt();
String address1;
int price1;
int area1;
int numBedroom1;
// Temp variable to accumulate the sum
//double sum = 0.0;
//Read the data line by line and build the
//array lists containing names and incomes
for (int k = 0; k < numRecords; k++)
{
address1 = myFileIn.next();
price1 = myFileIn.nextInt();
area1 = myFileIn.nextInt();
numBedroom1 = myFileIn.nextInt();
House house1 = new House(address1, price1, area1, numBedroom1);
houseList.add(house1);
}
// Close the input file
myFileIn.close();
}
public String getHouses(Criteria c)
{
String result = "";
for(int i = 0; i < houseList.size(); i++)
{
House h1 = houseList.get(i);
if (h1.satisfies(c))
{
result = result + h1.toString();
}
}
return result;
}
public void printHouses(Criteria c)
{
System.out.println(getHouses(c));
}
}
My file is in the same package, as I am using eclipse, but I keep getting "File: houses.txt is not found". To be thourough, the error I get is :
File: houses.txt is not found
Exception in thread "main" java.lang.NullPointerException
at project205.HouseList.<init>(HouseList.java:29)
at project205.HouseListTester.main(HouseListTester.java:7)
If anyone could even point me in the direction of what I'm missing here I would greatly appreciate it!
This may help you:
//creating File instance to reference text file in Java
File text = new File("<file location>/houses.txt");
//Creating Scanner instnace to read File in Java
Scanner scnr = new Scanner(text);
//Reading each line of file using Scanner class
while(scnr.hasNextLine()){
//process file
}
Use
System.getProperty("user.dir") + System.getProperty("file.separator") + "houses.txt"
to get the file path if houses.txt and the class file from which you are trying to access shares the same directory.
you can modify
myFileIn = new Scanner(new File("houses.txt"));
//to
myFileIn = new Scanner(new File(System.getProperty("user.dir") + System.getProperty("file.separator") + "houses.txt"));
//or
myFileIn = new Scanner(new File(System.getProperty("file.separator") + "houses.txt"));
Other case is that the file is in some other directory. In this scenario, provide relative path of this file ex.
//current dir is c: and your file is in d: then do
myFileIn = new Scanner(new File("addRelativeFilePathHere" + "houses.txt"));
Above, you need to end addRelativeFilePathHere with file.separator or prefix houses.txt with file separator.
This link to see what these properties points to and their meanings and for more inormation
http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html and
http://docs.oracle.com/javase/7/docs/api/java/io/File.html

Categories

Resources