I'm trying to Save/Load the array of objects to/from a plain .txt file. I know very little about serialization, but I think I have correctly used it to write the Array of objects to a .txt file. The .txt file is completely unreadable (in normal english) when opened separately. Am I writing it to a file correctly? and how do I go about reading it into the program?
public class HotelObjects {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String command;
Scanner input = new Scanner(System.in);
Room[] myHotel = new Room[10];
for (int x = 0; x < myHotel.length; x++) {
myHotel[x] = new Room();
}
String roomName;
int roomNum = 0;
while (roomNum < 11) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter command : ");
command = input.next();
command = command.toLowerCase();
if (command.charAt(0) == 'v') {
viewCustomers(myHotel);
}
if (command.charAt(0) == 'a') {
addCustomers(myHotel);
}
if (command.charAt(0) == 'e') {
emptyRooms(myHotel);
}
if (command.charAt(0) == 's') {
storeData(myHotel);
}
}
}
private static void viewCustomers(Room hotelRef []) {
for (int x = 0; x < 10; x++) {
System.out.println("room " + x + " occupied by " + hotelRef[x].getName());
}
}
private static void addCustomers(Room myHotel[]) {
String roomName;
int roomNum;
System.out.println("Enter room number (0-10) or 11 to stop:");
Scanner input = new Scanner(System.in);
roomNum = input.nextInt();
System.out.println("Enter name for room " + roomNum + " :");
roomName = input.next();
myHotel[roomNum].setName(roomName);
}
private static void emptyRooms(Room[] myHotel) {
for (int x = 0; x < 10; x++ )
if (myHotel[x].getName().equals("e"))System.out.println("room " + x + " is empty");
}
private static void storeData(Room [] myHotel) {
try{
FileOutputStream fos= new FileOutputStream("C:\\Users\\Ganz\\Documents\\NetBeansProjects\\HotelObjects\\HotelObject.dat");
ObjectOutputStream oos= new ObjectOutputStream(fos);
oos.writeObject(myHotel);
oos.close();
fos.close();
}catch(IOException ioe){
}
}
}
Here is the Room class (if needed):
public class Room implements Serializable {
private String mainName;
int guestsInRoom;
public Room() {
mainName = "e";
System.out.println("made a room ");
}
public void setName(String aName) {
mainName = aName;
}
public String getName() {
return mainName;
}
}
Use ObjectInputStream and a cast to load the array back from the file. And you need to flush the stream at the end of writing to it (before closing it).
The result of writing an ObjectOutputStream is supposed to be machine-readable and not human readable. To read it back in, use:
FileInputStream fis = new FileInputStream("C:\\Users\\Ganz\\Documents\\NetBeansProjects\\HotelObjects\\HotelObject.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
Hotel hotel = (Hotel) ois.readObject();
The output of an ObjectOutputStream is meant to be machine readable therefore it would not necessarily be human readable. When using closeable resources you should aim to use them within a try block prior to Java 1.7 and close the resource in the finally block of that try or if using 1.7+ a try-with-resources statement. This is to ensure that the resource is closed even in the event of an exception being thrown;
String path = "C:\\Users\\Ganz\\Documents\\NetBeansProjects\\HotelObjects\\HotelObject.dat";
try (FileInputStream fileInput = new FileInputStream(path); ObjectInputStream inputStream= new ObjectInputStream(fileInput)) {
// Cast the Object returned from the stream to a Hotel object
Hotel hotel = (Hotel) inputStream.readObject();
} catch (FileNotFoundException ex) {
// TODO: Exception handling here
} catch (IOException ex) {
// TODO: Exception handling here
}
If you don't feel the default serialized form suits your need then you can create your own. If so look up how to create a custom serialized form.
Related
First I am sorry for all the questions but I am at a loss and have spent the last week working on this. I am new to the community so please work with me while I learn the format that I need to have in place.
Okay so I am working on my final project for a class and I have been given a help document and two .txt files. I have the .txt files on the right level where they can be called from any computer. I have also gotten my code to where it calls the right array to get a new submenu to come up after selection from the main menu. From there I am having problems calling a method (showdata) to have a JOptionPane pop up with an alert that must be displayed if there is a call for it from the .txt file namely it will have (*****) in front of it. I also have to add an option for the user to go back to the main menu instead of it just closing the program but I am unsure where I can put this option. I don't know if I should add it in the default loop or in my switch statement. Any help would be great. Thanks so much.
I have now included my .txt files below.
My main code is:
import java.util.Scanner;
public class Monitor {
private static Scanner usrch = new Scanner(System.in);
/**
*
* #param args
*/
public static void main(String[] args) {
AnimalsHabitat methodCall = new AnimalsHabitat();
try {
int userChoice = mainMenu();
switch(userChoice) {
case 1:
System.out.println("Please pick the animal you would like to monitor: ");
System.out.println("");
methodCall.askForWhichDetails("animals");
System.out.println("Press 0 to go back.");
break;
case 2:
System.out.println("Please pick the habitat you would like to monitor: ");
System.out.println("");
methodCall.askForWhichDetails("habitats");
System.out.println("Press 0 to go back.");
break;
case 3:
System.out.println("Have a nice day!");
System.exit(0);
break;
default:
int loopError = 0;
while (loopError < 3) {
loopError++;
if (loopError == 3) {
System.out.println("Error in program loop, exiting program.");
System.exit(0);
}
}
}
}
catch (Exception e) {
System.out.println("Wrong input " + e.getMessage());
}
}
public static int mainMenu() {
System.out.println("Welcome to the Zoo Monitoring System!");
System.out.println("Please select what you would like to monitor: ");
System.out.println("");
System.out.println("1.) Animals");
System.out.println("2.) Habitats");
System.out.println("3.) Exit program");
int userChoice = Integer.parseInt(usrch.nextLine());
return userChoice;
}
}
My help code is:
import java.util.Scanner;
import java.io.IOException;
import java.io.FileInputStream;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class AnimalsHabitat {
private String filePath;
final private Scanner scnr;
public AnimalsHabitat() {
filePath = "";
scnr = new Scanner(System.in);
}
public void askForWhichDetails(String fileName) throws IOException {
FileInputStream fileByteStream = null; // File input stream
Scanner inFS = null; // Scanner object
String textLine = null;
ArrayList aList1 = new ArrayList();
int i = 0;
int option = 0;
boolean bailOut = false;
// Try to open file
fileByteStream = new FileInputStream(filePath + fileName + ".txt");
inFS = new Scanner(fileByteStream);
while (inFS.hasNextLine() && bailOut == false) {
textLine = inFS.nextLine();
if (textLine.contains("Details")) {
i += 1;
System.out.println(i + ". " + textLine);
ArrayList aList2 = new ArrayList();
for (String retval : textLine.split(" ")) {
aList2.add(retval);
}
String str = aList2.remove(2).toString();
aList1.add(str);
} else {
System.out.print("Enter selection: ");
option = scnr.nextInt();
System.out.println("");
if (option <= i) {
String detailOption = aList1.remove(option - 1).toString();
showData(fileName, detailOption);
bailOut = true;
}
break;
}
}
// Done with file, so try to close it
fileByteStream.close(); // close() may throw IOException if fails
}
public void showData(String fileName, String detailOption) throws IOException {
FileInputStream fileByteStream = null; // File input stream
Scanner inFS = null; // Scanner object
String textLine = null;
String lcTextLine = null;
String alertMessage = "*****";
int lcStr1Len = fileName.length();
String lcStr1 = fileName.toLowerCase().substring(0, lcStr1Len - 1);
int lcStr2Len = detailOption.length();
String lcStr2 = detailOption.toLowerCase().substring(0, lcStr2Len - 1);
boolean bailOut = false;
// Try to open file
fileByteStream = new FileInputStream(filePath + fileName + ".txt");
inFS = new Scanner(fileByteStream);
while (inFS.hasNextLine() && bailOut == false) {
textLine = inFS.nextLine();
lcTextLine = textLine.toLowerCase();
if (lcTextLine.contains(lcStr1) && lcTextLine.contains(lcStr2)) {
do {
System.out.println(textLine);
textLine = inFS.nextLine();
if (textLine.isEmpty()) {
bailOut = true;
}
if (textLine.contains(alertMessage)) {
JOptionPane.showMessageDialog(null, textLine.substring(5));
}
} while (inFS.hasNextLine() && bailOut == false);
}
}
// Done with file, so try to close it
fileByteStream.close(); // close() may throw IOException if fails
}
void showData() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
This is my animals.txt
Details on lions
Details on tigers
Details on bears
Details on giraffes
Animal - Lion
Name: Leo
Age: 5
*****Health concerns: Cut on left front paw
Feeding schedule: Twice daily
Animal - Tiger
Name: Maj
Age: 15
Health concerns: None
Feeding schedule: 3x daily
Animal - Bear
Name: Baloo
Age: 1
Health concerns: None
*****Feeding schedule: None on record
Animal - Giraffe
Name: Spots
Age: 12
Health concerns: None
Feeding schedule: Grazing
This is my habitats.txt:
Details on penguin habitat
Details on bird house
Details on aquarium
Habitat - Penguin
Temperature: Freezing
*****Food source: Fish in water running low
Cleanliness: Passed
Habitat - Bird
Temperature: Moderate
Food source: Natural from environment
Cleanliness: Passed
Habitat - Aquarium
Temperature: Varies with output temperature
Food source: Added daily
*****Cleanliness: Needs cleaning from algae
Does this work for you?
Monitor.java
import java.util.Scanner;
public class Monitor
{
private static Scanner usrch = new Scanner(System.in);
/**
*
* #param args
*/
public static void main(String[] args)
{
AnimalsHabitat methodCall = new AnimalsHabitat();
try
{
int userChoice = mainMenu();
switch(userChoice)
{
case 1:
System.out.println("Please pick the animal you would like to monitor: ");
System.out.println("");
methodCall.askForWhichDetails("animals");
break;
case 2:
System.out.println("Please pick the habitat you would like to monitor: ");
System.out.println("");
methodCall.askForWhichDetails("habitats");
break;
case 3:
System.out.println("Have a nice day!");
System.exit(0);
break;
default:
int loopError = 0;
while (loopError < 3)
{
loopError++;
if (loopError == 3)
{
System.out.println("Error in program loop, exiting program.");
System.exit(0);
}
}
}
}
catch (Exception e)
{
System.out.println("Wrong input " + e.getMessage());
}
}
public static int mainMenu()
{
System.out.println("Welcome to the Zoo Monitoring System!");
System.out.println("Please select what you would like to monitor: ");
System.out.println("");
System.out.println("1.) Animals");
System.out.println("2.) Habitats");
System.out.println("3.) Exit program");
int userChoice = Integer.parseInt(usrch.nextLine());
return userChoice;
}
}
AnimalsHabitat.java
import java.util.Scanner;
import java.io.IOException;
import java.io.FileInputStream;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class AnimalsHabitat
{
private String filePath;
final private Scanner scnr;
public AnimalsHabitat()
{
filePath = "";
scnr = new Scanner(System.in);
}
public void askForWhichDetails(String fileName) throws IOException
{
FileInputStream fileByteStream = null; // File input stream
Scanner inFS = null; // Scanner object
String textLine = null;
ArrayList aList1 = new ArrayList();
int i = 0;
int option = 0;
boolean bailOut = false;
// Try to open file
fileByteStream = new FileInputStream(filePath + fileName + ".txt");
inFS = new Scanner(fileByteStream);
while (inFS.hasNextLine() && bailOut == false)
{
textLine = inFS.nextLine();
if (textLine.contains("Details"))
{
i += 1;
System.out.println(i + ". " + textLine);
ArrayList aList2 = new ArrayList();
for (String retval : textLine.split(" "))
{
aList2.add(retval);
}
String str = aList2.remove(2).toString();
aList1.add(str);
}
else
{
while(option != (i + 1))
{
System.out.print("Enter selection or enter " + (i + 1) + " to exit: ");
option = scnr.nextInt();
System.out.println("");
if (option <= i)
{
String detailOption = aList1.remove(option - 1).toString();
showData(fileName, detailOption);
}
}
break;
}
}
// Done with file, so try to close it
fileByteStream.close(); // close() may throw IOException if fails
}
public void showData(String fileName, String detailOption) throws IOException
{
FileInputStream fileByteStream = null; // File input stream
Scanner inFS = null; // Scanner object
String textLine = null;
String lcTextLine = null;
String alertMessage = "*****";
int lcStr1Len = fileName.length();
String lcStr1 = fileName.toLowerCase().substring(0, lcStr1Len - 1);
int lcStr2Len = detailOption.length();
String lcStr2 = detailOption.toLowerCase().substring(0, lcStr2Len - 1);
boolean bailOut = false;
// Try to open file
fileByteStream = new FileInputStream(filePath + fileName + ".txt");
inFS = new Scanner(fileByteStream);
while (inFS.hasNextLine() && bailOut == false)
{
textLine = inFS.nextLine();
lcTextLine = textLine.toLowerCase();
if (lcTextLine.contains(lcStr1) && lcTextLine.contains(lcStr2))
{
do
{
System.out.println(textLine);
textLine = inFS.nextLine();
if (textLine.isEmpty())
{
bailOut = true;
}
if (textLine.contains(alertMessage))
{
JOptionPane.showMessageDialog(null, textLine.substring(5));
}
}
while (inFS.hasNextLine() && bailOut == false);
}
}
// Done with file, so try to close it
fileByteStream.close(); // close() may throw IOException if fails
}
void showData()
{
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
Run example
javac AnimalsHabitat.java Monitor.java && java Monitor
Here is an example of some menu and submenu selection
package com.hnb;
public class Monitor {
public Monitor(FileParser fileParser) {
final Menu main = new Menu(fileParser.getOptions());
System.out.println("Welcome to the Zoo Monitoring System!");
MenuSelection selection = null;
Selection subselection = null;
do {
selection = main.displaySubMenu();
if(selection.isValid()){
do {
final Menu submenu = new Menu(selection.getSelection());
subselection = submenu.display();
if (subselection.isValid()) {
final Monitorable item = (Monitorable) subselection.getSelection();
System.out.println(item);
item.showAsterisk();
}
} while (!subselection.isExit());
}
} while (!selection.isExit());
}
public static void main(String[] args) {
new Monitor(new FileParser());
}
}
I am trying to take an initial CSV file, pass it through a class that checks another file if it has an A or a D to then adds or deletes the associative entry to an array object.
example of pokemon.csv:
1, Bulbasaur
2, Ivysaur
3, venasaur
example of changeList.csv:
A, Charizard
A, Suirtle
D, 2
That being said, I am having a lot of trouble getting the content of my new array to a new CSV file. I have checked to see whether or not my array and class files are working properly. I have been trying and failing to take the final contents of "pokedex1" object array into the new CSV file.
Main File
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class PokedexManager {
public static void printArray(String[] array) {
System.out.print("Contents of array: ");
for(int i = 0; i < array.length; i++) {
if(i == array.length - 1) {
System.out.print(array[i]);
}else {
System.out.print(array[i] + ",");
}
}
System.out.println();
}
public static void main(String[] args) {
try {
//output for pokedex1 using PokemonNoGaps class
PokemonNoGaps pokedex1 = new PokemonNoGaps();
//initializes scanner to read from csv file
String pokedexFilename = "pokedex.csv";
File pokedexFile = new File(pokedexFilename);
Scanner pokescanner = new Scanner(pokedexFile);
//reads csv file, parses it into an array, and then adds new pokemon objects to Pokemon class
while(pokescanner.hasNextLine()) {
String pokeLine = pokescanner.nextLine();
String[] pokemonStringArray = pokeLine.split(", ");
int id = Integer.parseInt(pokemonStringArray[0]);
String name = pokemonStringArray[1];
Pokemon apokemon = new Pokemon(id, name);
pokedex1.add(apokemon);
}
//opens changeList.csv file to add or delete entries from Pokemon class
String changeListfilename = "changeList.csv";
File changeListFile = new File(changeListfilename);
Scanner changeScanner = new Scanner(changeListFile);
//loads text from csv file to be parsed to PokemonNoGaps class
while(changeScanner.hasNextLine()) {
String changeLine = changeScanner.nextLine();
String[] changeStringArray = changeLine.split(", ");
String action = changeStringArray[0];
String nameOrId = changeStringArray[1];
//if changList.csv file line has an "A" in the first spot add this entry to somePokemon
if(action.equals("A")) {
int newId = pokedex1.getNewId();
String name = nameOrId;
Pokemon somePokemon = new Pokemon(newId, name);
pokedex1.add(somePokemon);
}
//if it has a "D" then send it to PokemonNoGaps class to delete the entry from the array
else { //"D"
int someId = Integer.parseInt(nameOrId);
pokedex1.deleteById(someId);
}
//tests the action being taken and the update to the array
//System.out.println(action + "\t" + nameOrId + "\n");
System.out.println(pokedex1);
//*(supposedly)* prints the resulting contents of the array to a new csv file
String[] pokemonList = changeStringArray;
try {
String outputFile1 = "pokedex1.csv";
FileWriter writer1 = new FileWriter(outputFile1);
writer1.write(String.valueOf(pokemonList));
} catch (IOException e) {
System.out.println("\nError writing to Pokedex1.csv!");
e.printStackTrace();
}
}
//tests final contents of array after being passed through PokemonNoGaps class
//System.out.println(pokedex1);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
PokemonNoGaps class file:
public class PokemonNoGaps implements ChangePokedex {
private Pokemon[] pokedex = new Pokemon[1];
private int numElements = 0;
private static int id = 0;
// add, delete, search
#Override
public void add(Pokemon apokemon) {
// if you have space
this.pokedex[this.numElements] = apokemon;
this.numElements++;
// if you don't have space
if(this.numElements == pokedex.length) {
Pokemon[] newPokedex = new Pokemon[ this.numElements * 2]; // create new array
for(int i = 0; i < pokedex.length; i++) { // transfer all elements from array into bigger array
newPokedex[i] = pokedex[i];
}
this.pokedex = newPokedex;
}
this.id++;
}
public int getNewId() {
return this.id + 1;
}
#Override
public void deleteById(int id) {
for(int i = 0; i < numElements; i++) {
if(pokedex[i].getId() == id) {
for(int j = i+1; j < pokedex.length; j++) {
pokedex[j-1] = pokedex[j];
}
numElements--;
pokedex[numElements] = null;
}
}
}
public Pokemon getFirstElement() {
return pokedex[0];
}
public int getNumElements() {
return numElements;
}
public String toString() {
String result = "";
for(int i = 0; i < this.numElements; i++) {
result += this.pokedex[i].toString() + "\n";
}
return result;
}
}
Excpeted output:
1, Bulbasaur
3, Venasaur
4, Charizard
5, Squirtle
Am i using the wrong file writer? Am I calling the file writer at the wrong time or incorrectly? In other words, I do not know why my output file is empty and not being loaded with the contents of my array. Can anybody help me out?
I spotted a few issues whilst running this. As mentioned in previous answer you want to set file append to true in the section of code that writes to the new pokedx1.csv
try {
String outputFile1 = "pokedex1.csv";
FileWriter fileWriter = new FileWriter(prefix+outputFile1, true);
BufferedWriter bw = new BufferedWriter(fileWriter);
for(String pokemon : pokedex1.toString().split("\n")) {
System.out.println(pokemon);
bw.write(pokemon);
}
bw.flush();
bw.close();
} catch (IOException e) {
System.out.println("\nError writing to Pokedex1.csv!");
e.printStackTrace();
}
I opted to use buffered reader for the solution. Another issue I found is that your reading pokedex.csv but the file is named pokemon.csv.
String pokedexFilename = "pokemon.csv";
I made the above change to fix this issue.
On a side note I noticed that you create several scanners to read the two files. With these types of resources its good practice to call the close method once you have finished using them; as shown below.
Scanner pokescanner = new Scanner(pokedexFile);
// Use scanner code here
// Once finished with scanner
pokescanner.close();
String outputFile1 = "pokedex1.csv";
FileWriter writer1 = new FileWriter(outputFile1);
appears to be within your while loop so a new file will be created every time.
Either use the FileWriter(File file, boolean append) constructor or create before the loop
I'm beginner in java and kinda stuck in these two problems so I'm trying to
let the program read from a CSV file line by line.
So in the file I have first row as String and the column is double.
So the problem is when it read first line It's reading the titles as double and it gives me an error.
By the way it is CSV file
The error i got are these below
Exception in thread "main" java.lang.NumberFormatException: For input string: "CLOSE" This is first error
Second error >> at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1222) –
Third error >> at java.lang.Double.parseDouble(Double.java:510)
Forth error >>> at AlgorithmTrader.ReadInputData(AlgorithmTrader.java:63)
Fifth Error >> at AlgorithmTrader.Run(AlgorithmTrader.java:16)
Last error >> SimpleAlgorithmTradingPlatform.main(SimpleAlgorithmTradingPlatform.java:15)
So the first row in the file has TIMESTAMP | Close | High | Low | open | volume and under each of those row there is numbers as double except volume has integer numbers
Your suggestion will appreciated. Thanks
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class AlgorithmTrader {
public void Run() {
ReadInputData();
}
public void ReadInputData() {
// create object of scanner class for user input
Scanner scan = new Scanner(System.in);
// declare file name for input file
String inputFileName = "";
// input from user for input file
System.out.print("Enter Input File Name: ");
inputFileName = scan.nextLine();
try {
PrintWriter pw = new PrintWriter("output.csv");// to open the file
// create a new file
File file = new File(inputFileName);
// create a new scanner object to read file
Scanner readFile = new Scanner(file);
// for each line data
String line = "";
line = readFile.nextLine();//skip the first line
while (readFile.hasNextLine()) {
readFile.nextLine();
// pass file to scanner again
readFile = new Scanner(file);
ArrayList<String> list = new ArrayList<String>();
// read stock data line by line
while (readFile.hasNextLine()) {
// read line from file
line = readFile.nextLine();
// split line data into tokens
String result[] = line.split(",");
// variables to create a Stock object
String timestamp = result[0];
double close = Double.parseDouble(result[1]);
double high = Double.parseDouble(result[2]);
double low = Double.parseDouble(result[3]);
double open = Double.parseDouble(result[4]);
int volume = Integer.parseInt(result[5]);
// store data into ArrayList
list.add(readFile.next());
pw.print(list.add(readFile.next()));
Stock stock = new Stock(timestamp, close, high, low, open, volume);
}// end of while to read file
//close readFile object
readFile.close();
pw.close();//close file
}
} catch (FileNotFoundException e1) {
System.out.println(" not found.\n");
System.exit(0);
} catch (IOException e2) {
System.out.println("File can't be read\n");
}
}
}
I have another file Stock class
public class Stock {
String timestamp;
double close;
double high;
double low;
double open;
int volume;
Stock(String t, double c, double h, double l, double o, int v) {
timestamp = t;
close = c;
high = h;
low = l;
open = o;
volume = v;
}
public void settimestamp(String t) {
this.timestamp = t;
}
public void setclose(double c) {
this.close = c;
}
public void sethigh(double h) {
this.high = h;
}
public void setopen(double o) {
this.open = o;
}
public void setvolume(int v) {
this.volume = v;
}
public String gettimestamp() {
return timestamp;
}
public double close() {
return close;
}
public double high() {
return high;
}
public int volume() {
return volume;
}
}
And The main method in another file as well
import java.text.DecimalFormat;
public class SimpleAlgorithmTradingPlatform {
public static void main(String[] args) {
DecimalFormat fmt = new DecimalFormat("#0.00"); // to get the DecimalFormat
AlgorithmTrader test = new AlgorithmTrader();
test.Run();
}
}
You are you having NumberFormatException because here
line = readFile.nextLine();//skip the first line
you are not skipping first line.
You'd better use BufferedReader instead of Scanner after getting file name. I have corrected you code a bit.
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class AlgorithmTrader {
public void Run() {
ReadInputData();
}
public void ReadInputData() {
// create object of scanner class for user input
Scanner scan = new Scanner(System.in);
// declare file name for input file
String inputFileName = "";
// input from user for input file
System.out.print("Enter Input File Name: ");
inputFileName = scan.nextLine();
// create a new file
File csvFile = new File(inputFileName);
String line;
ArrayList<Stock> list = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
System.out.println("Reading file " + csvFile);
System.out.println("Skipping title of the CSV file");
// Skip first line because it is title
br.readLine();
System.out.println("Converting line to Stock");
while ((line = br.readLine()) != null) {
String result[] = line.split(",");
String timestamp = result[0];
double close = Double.parseDouble(result[1]);
double high = Double.parseDouble(result[2]);
double low = Double.parseDouble(result[3]);
double open = Double.parseDouble(result[4]);
int volume = Integer.parseInt(result[5]);
list.add(new Stock(timestamp, close, high, low, open, volume));
}
System.out.println("Done");
} catch (FileNotFoundException e1) {
System.out.println(" not found.");
System.exit(0);
} catch (IOException e2) {
System.out.println("File can't be read");
}
}
}
It would be nice to see a fictional example of the contents within your CSV file but please spare us any additional comments. ;)
It looks like your errors (and probably all of them) are most likely coming from your Stock Class. That's for another posted question however your getters and setters need attention. Some are missing as well but perhaps this is by choice.
You should be able to carry out this task with one Scanner object and one while loop. Use the same Scanner object for User input and file reading, it's reinitialized anyways.
The code below is one way to do it:
ArrayList<String> list = new ArrayList<>();
// create object of scanner class for user input
// and File Reading.
Scanner scan = new Scanner(System.in);
// declare file name for input file
String inputFileName = "";
// input from User for input file name.
System.out.print("Enter Input File Name: ");
inputFileName = scan.nextLine();
String tableHeader = "";
try {
// create a new file with PrintWriter in a
PrintWriter pw = new PrintWriter("output.csv");
File file = new File(inputFileName);
// Does the file to read exist?
if (!file.exists()) {
System.err.println("File Not Found!\n");
System.exit(0);
}
// create a new scanner object to read file
scan = new Scanner(file);
// for each line data
String line = "";
tableHeader = scan.nextLine();
String newline = System.getProperty("line.separator");
// Print the Table Header to our new file.
pw.print(tableHeader + newline);
while (scan.hasNextLine()) {
line = scan.nextLine();
// Make sure we don't deal with a blank line.
if (line.equals("") || line.isEmpty()) {
continue;
}
// split line data into a String Array.
// Not sure if there is a space after
// comma delimiter or not but I'm guessing
// there is. If not then remove the space.
String result[] = line.split(", ");
// variables to create a Stock object
String timestamp = "";
double close = 0.0;
double high = 0.0;
double low = 0.0;
double open = 0.0;
int volume = 0;
// Make sure there are enough array elements
// from our split string to fullfil all our
// variables. Maybe some data is missing.
int resLen = result.length;
if (resLen > 0) {
if (resLen >= 1) { timestamp = result[0]; }
if (resLen >= 2) { close = Double.parseDouble(result[1]); }
if (resLen >= 3) { high = Double.parseDouble(result[2]); }
if (resLen >= 4) { low = Double.parseDouble(result[3]); }
if (resLen >= 5) { open = Double.parseDouble(result[4]); }
if (resLen >= 6) { volume = Integer.parseInt(result[5]); }
}
// store data into ArrayList.
// Convert the result Array to a decent readable string.
String resString = Arrays.toString(result).replace("[", "").replace("]", "");
list.add(resString);
// Print the string to our output.csv file.
pw.print(resString + System.getProperty("line.separator"));
//Stock stock = new Stock(timestamp, close, high, low, open, volume);
}
//close file
scan.close();
pw.close();
}
catch (IOException ex ){
System.err.println("Can Not Read File!\n" + ex.getMessage() + "\n");
System.exit(0);
}
// Example to show that the ArrayList actually
// contains something....
// Print data to Console Window.
tableHeader = tableHeader.replace(" | ", "\t");
tableHeader = "\n" + tableHeader.substring(0, 10) + "\t" + tableHeader.substring(10);
System.out.println(tableHeader);
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).replace(", ", "\t"));
}
I'm trying to read a text file to get a version number but for some reason no matter what I put in the text file it always returns 0 (zero).
The text file is called version.txt and it contains no spaces or letters, just 1 character that is a number. I need it to return that number. Any ideas on why this doesn't work?
static int i;
public static void main(String[] args) {
String strFilePath = "/version.txt";
try
{
FileInputStream fin = new FileInputStream(strFilePath);
DataInputStream din = new DataInputStream(fin);
i = din.readInt();
System.out.println("int : " + i);
din.close();
}
catch(FileNotFoundException fe)
{
System.out.println("FileNotFoundException : " + fe);
}
catch(IOException ioe)
{
System.out.println("IOException : " + ioe);
}
}
private final int VERSION = i;
Here is the default solution that i use whenever i require to read a text file.
public static ArrayList<String> readData(String fileName) throws Exception
{
ArrayList<String> data = new ArrayList<String>();
BufferedReader in = new BufferedReader(new FileReader(fileName));
String temp = in.readLine();
while (temp != null)
{
data.add(temp);
temp = in.readLine();
}
in.close();
return data;
}
Pass the file name to readData method. You can then use for loop to read the only line in the arraylist, and can use the same loop to read multiple lines from different file...I mean do whatever you like with the arraylist.
Please don't use a DataInputStream
Per the linked Javadoc, it lets an application read primitive Java data types from an underlying input stream in a machine-independent way. An application uses a data output stream to write data that can later be read by a data input stream.
You want to read a File (not data from a data output stream).
Please do use try-with-resources
And since you seem to want an ascii integer, I'd suggest you use a Scanner.
public static void main(String[] args) {
String strFilePath = "/version.txt";
File f = new File(strFilePath);
try (Scanner scanner = new Scanner(f)) {
int i = scanner.nextInt();
System.out.println(i);
} catch (Exception e) {
e.printStackTrace();
}
}
Use an initializing block
An initializing block will be copied into the class constructor, in your example remove public static void main(String[] args), something like
private int VERSION = -1; // <-- no more zero!
{
String strFilePath = "/version.txt";
File f = new File(strFilePath);
try (Scanner scanner = new Scanner(f)) {
VERSION = scanner.nextInt(); // <-- hope it's a value
System.out.println("Version = " + VERSION);
} catch (Exception e) {
e.printStackTrace();
}
}
Extract it to a method
private final int VERSION = getVersion("/version.txt");
private static final int getVersion(String strFilePath) {
File f = new File(strFilePath);
try (Scanner scanner = new Scanner(f)) {
VERSION = scanner.nextInt(); // <-- hope it's a value
System.out.println("Version = " + VERSION);
return VERSION;
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
or even
private final int VERSION = getVersion("/version.txt");
private static final int getVersion(String strFilePath) {
File f = new File(strFilePath);
try (Scanner scanner = new Scanner(f)) {
if (scanner.hasNextInt()) {
return scanner.nextInt();
}
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
I had this program with which i have to check if the value the user entered is present in the text file i created in the source file. However it throws me an error everytime i try to call the method with IOException. Please help me out thanks.
import java.util.*;
import java.io.*;
public class chargeAccountModi
{
public boolean sequentialSearch ( double chargeNumber ) throws IOException
{
Scanner keyboard= new Scanner(System.in);
int index = 0;
int element = -1;
boolean found = false;
System.out.println(" Enter the Charge Account Number : " );
chargeNumber = keyboard.nextInt();
int[] tests = new int[18];
int i = 0;
File file = new File ("Names.txt");
Scanner inputFile = new Scanner(file);
while(inputFile.hasNext() && i < tests.length )
{
tests [i] = inputFile.nextInt();
i++;
}
inputFile.close();
for ( index = 0 ; index < tests.length ; index ++ )
{
if ( tests[index] == chargeNumber )
{
found = true;
element = index;
}
}
return found;
}
public static void main(String[]Args)
{
double chargeNumber = 0;
chargeAccountModi object1 = new chargeAccountModi();
try
{
object1.sequentialSearch(chargeNumber);
}
catch (IOException ioe)
{
}
System.out.println(" The search result is : " + object1.sequentialSearch (chargeNumber));
}
}
After looking on your method sequentialSearch there is everythink ok. But try to change main:
But remember that in your Names.txt file you should have only numbers because you use scanner.nextInt();, so there should be only numbers or method will throw exeption InputMismatchException.
Check also path to Names.txt file you should have it on classpath because you use relative path in code File file = new File ("Names.txt"); Names.txt should be in the same folder.
public static void main(String[]Args)
{
double chargeNumber = 0;
chargeAccountModi object1 = new chargeAccountModi();
try
{
System.out.println(" The search result is : " + object1.sequentialSearch(chargeNumber));
}
catch (IOException ioe)
{
System.out.println("Exception!!!");
ioe.printStackTrace();
}
}
Few tips and suggestions:
First of all: Don't forget to close the Scanner objects! (you left one unclosed)
Second of all: Your main method is highly inefficient, you are using two loops, in the first one you read and store variables, in the second one you check for a match, you can do both at the same time (I've written an alternative method for you)
Third little thing: The variable "element" is not used at all in your code, I've removed it in the answer.
And last but not least: The file "Names.txt" needs to be located (since you've only specificied it's name) in the root folder of your project, since you mention an IOException, I figure that's what's wrong with the app. If your project is called Accounts, then it's a folder called Accounts with it's source and whatever else is part of your project, make sure the file "Accounts/Names.txt" exists! and that it is in the desired format.
import java.util.*;
import java.io.*;
public class ChargeAccountModi {
public boolean sequentialSearch(double chargeNumber) throws IOException {
Scanner keyboard= new Scanner(System.in);
int index = 0;
boolean found = false;
System.out.print("Enter the Charge Account Number: " );
chargeNumber = keyboard.nextInt();
int[] tests = new int[18];
int i = 0;
File file = new File ("Names.txt");
Scanner inputFile = new Scanner(file);
while(inputFile.hasNext() && i < tests.length ) {
tests [i] = inputFile.nextInt();
i++;
}
inputFile.close();
for (index = 0 ; index < tests.length ; index ++ ) {
if (tests[index] == chargeNumber) {
found = true;
}
}
keyboard.close();
return found;
}
public boolean sequentialSearchAlternative(double chargeNumber) throws IOException {
Scanner keyboard= new Scanner(System.in);
boolean found = false;
System.out.print("Enter the Charge Account Number: " );
chargeNumber = keyboard.nextInt();
int tests = 18;
int i = 0;
File file = new File ("Names.txt");
Scanner inputFile = new Scanner(file);
while(inputFile.hasNext() && i<tests) {
if (inputFile.nextInt() == chargeNumber) {
found = true;
break;
}
i++;
}
inputFile.close();
keyboard.close();
return found;
}
public static void main(String[] args) {
double chargeNumber = 0;
ChargeAccountModi object1 = new ChargeAccountModi();
try {
System.out.println("The search result is : " + object1.sequentialSearch(chargeNumber));
} catch (Exception e) {
//Handle the exceptions here
//The most likely exceptions are:
//java.io.FileNotFoundException: Names.txt - Cannot find the file
//java.util.InputMismatchException - If you type something other than a number
e.printStackTrace();
}
}
}