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
Related
import java.io.File;
import java.util.*;
public class AppendTool {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Input Directory to Append Values: ");
String dirInput = sc.nextLine();
System.out.println("Input value to append to Directory Files: ");
String valInput = sc.nextLine();
sc.close();
File path = new File(dirInput);
File [] files = path.listFiles();
for (int i = 0; i < files.length; i++){
if (files[i].isFile()){ //this line weeds out other directories/folders
System.out.println(files[i]);
int where = files[i].getName().lastIndexOf(".");
String result = valInput + files[i].getName().substring(0, where) + files[i].getName().substring(where);
System.out.println(result);
File dest = new File(result);
files[i].renameTo(dest);
System.out.println(files[i]);
}
}
}
}
This tool is designed to append a value to the beginning of the filename for every filename in a directory. It seems to append the value as it should, but it deletes the files from the directory rather than rename the existing file within the same directory. Any help would be appreciated.
To rename a file in the same directory, you can use:
Files.move(source, source.resolveSibling("newName.txt"),
StandardCopyOption.REPLACE_EXISTING);
Your result variable is weird, you can just:
String result = valInput + files[i].getName();
I'm not sure if I'm not entering my code the right way, or where the error in my actual code is. I'm relatively new to "try" "catch" and when I run the coverage of my code in Java it shows that after I enter the inputted string it goes straight to the error. Their is more than one class for this code's purpose but the code doesn't run through all of the classes before the error. The purpose of the code is to enter information about students and through the code determine if they match together. This class specifically is the main class of the program. The problem comes when i enter a string like "Abey," and I'll get the error.
ERROR:
Please give the student name:
Abey
java.io.FileNotFoundException: Abey (The system cannot find the file specified)
MY CODE
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class Match {
public static void main(String[] args) {
Student[] arr = new Student[100];
System.out.println("Please give the student name: ");
Scanner input = new Scanner(System.in);
String filename = input.next();
Scanner nameInput;
try {
nameInput = new Scanner(new FileReader(filename));
int i = 0;
while (nameInput.hasNextLine()) {
Scanner ab = new Scanner(nameInput.nextLine());
ab.useDelimiter("[\t-]");
String name = ab.next();
String gender = ab.next();
String date = ab.next();
Scanner birthDateReader = new Scanner(date);
birthDateReader.useDelimiter("-");
int month = birthDateReader.nextInt();
int day = birthDateReader.nextInt();
int year = birthDateReader.nextInt();
int quietTime = ab.nextInt();
int music = ab.nextInt();
int reading = ab.nextInt();
int chatting = ab.nextInt();
Date birthdate = new Date(month, day, year);
Preference pref = new Preference(quietTime, music, reading, chatting);
Student studentAdd = new Student(name, gender.charAt(0), birthdate, pref);
arr[i++] = studentAdd;
}
int max = i;
for (i = 0; i < max; i++) {
if (!arr[i].getMatch()) {
int bestScore = 0;
int bestMatch = 0;
for (int j = i + 1; j < max; j++) {
if (!arr[j].getMatch()) {
int tmp = arr[i].compare(arr[j]);
if (tmp > bestScore) {
bestScore = tmp;
bestMatch = j;
}
}
}
if (bestScore != 0) {
arr[i].setMatched(true);
arr[bestMatch].setMatched(true);
System.out.println(arr[i].getName() + " can match with " + arr[bestMatch].getName() + " with the score " + bestScore);
} else
if (!arr[i].getMatch())
System.out.println(arr[i].getName() + " Does not have any matches.");
}
}
input.close();
} catch (NoSuchElementException e) {
System.out.println(e);
} catch (FileNotFoundException e) {
System.out.println(e);
}
}
}
The process cannot find the Abey file relative to the working directory. Try to specify the full path:
File root = new File("/path/to/data/files");
...
String filename = ....;
File datafile = new File(root, filename);
try (FileReader reader = new FileReader(datafile)) {
....
}
The main Problem is, Program is searching as relative path. You need to provide the complete path of the file.
String completePath = "/opt/java/path/"
Scanner input = new Scanner(System.in);
String filename = input.next();
Scanner nameInput;
try {
nameInput = new Scanner (new FileReader(completePath+filename));
This will be the modified code for you.
Here completePath variable contains path of the folder on which you have stored files by student name.
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.
I am attempting to create a rather large program. One of the things that I need the program to do is read a text file and use it to fill in the values for multiple objects of an array. In the case of the program that i am about to post, each object of the array has three different data types that i need to fill in the values for by having my program read the text file and pull out the correct pieces of data from each line. I already know how to get my program to read a text file and print out the data line by line, but i do not know how to create a loop that will pick out specific pieces of data from a line in a text file and put them in the appropriate places for each object. The following program is a simplified version of a much larger program that is nearly complete. Any help on the matter would be greatly appreciated.
package cloneCounter;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class cloneCounter {
public String name;
public int age;
public double weight;
cloneCounter(String cloneName, int timeSpentLiving, double heaviness)
{
name = cloneName;
age = timeSpentLiving;
weight = heaviness;
}
public static void main(String[] args) {
cloneCounter [] clone = new cloneCounter[3];
//This is what the textfile looks like.
//Billy 22 188.25
//Sam 46 301.77
//John 8 51.22
//code that can read and print the textfile
String fileName = "data.txt";
Scanner inputStream = null;
System.out.println("The file " + fileName + "\ncontains the following lines:\n");
try
{
inputStream = new Scanner(new File("data.txt"));//The txt file is being read correctly.
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file " + fileName);
System.exit(0);
}
List<cloneCounter> clones = new ArrayList<cloneCounter>();
while (inputStream.hasNextLine()) {
String line = inputStream.nextLine();
String[] data = line.split(" ");
cloneCounter clone = new cloneCounter(data[0],Integer.parseInt(data[1]),Double.parseDouble(data[2]));
clones.add(clone);
}
}
inputStream.close();
//temporary placeholders to fill in the values for the objects until i can figure out how to import and implement the data from a text file
clone[0] = new cloneCounter ("Billy", 22, 188.25);
clone[1] = new cloneCounter ("Sam", 46, 301.77);
clone[2] = new cloneCounter ("John", 8, 51.22);
for(int i=0; i<3; i++)
{
System.out.println(clone[i].name + " " + clone[i].age + " " + clone[i].weight);
}
}
}
If your data is separated by single space then you can do the following:
List<cloneCounter> clones = new ArrayList<cloneCounter>();
while (inputStream.hasNextLine()) {
String line = inputStream.nextLine();
String[] data = line.split(" ");
cloneCounter clone = new cloneCounter(data[0],Integer.parseInt(data[1]),Double.parseDouble(data[2]));
clones.add(clone);
}
EDIT: Here is the full program just copy and paste it and it will work fine (tested):
package cloneCounter;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class cloneCounter {
public String name;
public int age;
public double weight;
cloneCounter(String cloneName, int timeSpentLiving, double heaviness)
{
name = cloneName;
age = timeSpentLiving;
weight = heaviness;
}
public static void main(String[] args) {
//This is what the textfile looks like.
//Billy 22 188.25
//Sam 46 301.77
//John 8 51.22
//code that can read and print the textfile
String fileName = "data.txt";
Scanner inputStream = null;
System.out.println("The file " + fileName + "\ncontains the following lines:\n");
try
{
inputStream = new Scanner(new File("data.txt"));//The txt file is being read correctly.
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file " + fileName);
System.exit(0);
}
List<cloneCounter> clones = new ArrayList<cloneCounter>();
while (inputStream.hasNextLine()) {
String line = inputStream.nextLine();
String[] data = line.split(" ");
cloneCounter clone = new cloneCounter(data[0],Integer.parseInt(data[1]),Double.parseDouble(data[2]));
clones.add(clone);
}
inputStream.close();
for(int i=0; i<3; i++)
{
System.out.println(clones.get(i).name + " " + clones.get(i).age + " " + clones.get(i).weight);
}
}
}
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.