NumberFormatException when reading CSV file in java - java

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(FloatingDecima‌​l.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(SimpleAlgorithmTradingPl‌​atform.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"));
}

Related

Scanner inside method dont ask for input

I ask user to insert an item name with extension ".txt" and if the item name is coresponding to the existing itemName.txt then user need to insert the location name with extension ".txt" where he want to "transfer" it .
if everithing is ok then the content from itemName.txt will be writen into the locationName.txt
My Main looks like this :
package victor;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
public class Main extends Item {
public Main(String location, Integer length, Integer height, Integer depth) {
super(location, length, height, depth);
}
public static void main(String[] args) throws IOException {
List<Item> itemList = new ArrayList<>();
List<Location> locationList = new ArrayList<>();
System.out.println("Welcome to create new:");
System.out.println("Please follow the steps:");
HashMap<Integer, String> menu = new HashMap<>();
menu.put(1, "Create Location");
menu.put(2, "Create Item");
menu.put(3, "Transfer to location");
menu.forEach((key, value) -> System.out.println(key + "- " + value));
int user_choice;
Scanner userInputMenu = new Scanner(System.in);
user_choice = userInputMenu.nextInt();
switch (user_choice) {
case 1:
createLocationPlusFile(locationList);
case 2:
createItemPlusFile(itemList);
case 3:
transferItemToLocation(itemList, locationList);
}
}
}
When user input from menu - 3 , program is closing Process finished with exit code 0.
Here is my Item Class with the method I wrote:
package victor;
import java.io.*;
import java.util.List;
import java.util.Scanner;
public class Item extends Location {
private String itemName;
private Integer kg;
private Integer length;
private Integer height;
private Integer depth;
public Item(String itemName, Integer kg, Integer length, Integer height, Integer depth) {
super();
this.itemName = itemName;
this.kg = kg;
this.length = length;
this.height = height;
this.depth = depth;
}
public Item() {
}
public Item(String location, Integer length, Integer height, Integer depth) {
super();
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public Integer getKg() {
return kg;
}
public void setKg(Integer kg) {
this.kg = kg;
}
public Integer getLength() {
return length;
}
public void setLength(Integer length) {
this.length = length;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
public Integer getDepth() {
return depth;
}
public void setDepth(Integer depth) {
this.depth = depth;
}
#Override
public String toString() {
return "Item{" +
"itemName='" + itemName + '\'' +
", kg=" + kg +
", length=" + length +
", height=" + height +
", depth=" + depth +
'}';
}
public static void createItemPlusFile(List<Item> itemList) throws NullPointerException, IOException {
int defaultLength = 80;
int defaultHeight = 205;
int defaultDepth = 120;
int defaultKg = 3500;
Scanner in1 = new Scanner(System.in);
System.out.println("Enter Item Name: ");
String itemName = in1.nextLine();
System.out.println("New Item created successfully!" + "\n" + itemName);
int inLength;
Scanner in2 = new Scanner(System.in);
System.out.println("Enter Item height: ");
int itemLength = in2.nextInt();
if (itemLength > defaultLength) {
System.out.println("Height that you added is to big, please use a height of max 205");
inLength = in2.nextInt();
} else {
System.out.println("Height inserted correctly! ");
}
int inHeight;
Scanner in3 = new Scanner(System.in);
System.out.println("Enter Item height: ");
int itemHeight = in3.nextInt();
if (itemHeight > defaultHeight) {
System.out.println("Height that you added is to big, please use a height of max 205");
inHeight = in3.nextInt();
} else {
System.out.println("Height inserted correctly! ");
}
int inDepth;
Scanner in4 = new Scanner(System.in);
System.out.println("Enter Item depth: ");
int itemDepth = in4.nextInt();
if (itemDepth > defaultDepth) {
System.out.println("Depth that you added is to big, please use a depth of max 120");
inDepth = in4.nextInt();
} else {
System.out.println("Depth inserted correctly! ");
}
int inKg;
Scanner in5 = new Scanner(System.in);
System.out.println("Enter Item kg: ");
int itemKg = in4.nextInt();
if (itemKg > defaultKg) {
System.out.println("kg that you added is to big, please use a depth of max 3500");
inDepth = in4.nextInt();
} else {
System.out.println("Kg inserted correctly! ");
}
Item item = new Item(itemName, itemKg, itemLength, itemHeight, itemDepth);
File file = new File(item.getItemName() + "CUSCAS001GRY-uk.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fileWriter = new FileWriter(item.getItemName() + "CUSCAS001GRY-uk.txt", true);
fileWriter.write(item + "\n");
fileWriter.close();
}
//this method I wrote, I expect to ask user to input the item and if item with this name exist then he insert the location where he want to "transfer" it .
public static void transferItemToLocation(List<Item> itemList, List<Location> locationList) throws IOException {
for (Item item : itemList) {
for (Location location : locationList) {
Scanner inputItemTransfer = new Scanner(System.in);
System.out.println("Insert the item you want to transfer + .txt extension!");
inputItemTransfer.nextLine();
if (inputItemTransfer.nextLine()
.equalsIgnoreCase(item + ".txt")) {
Scanner inputTransferToLocation = new Scanner(System.in);
System.out.println("Insert the location where you want to transfer the item");
inputTransferToLocation.nextLine();
if (inputTransferToLocation.nextLine()
.equalsIgnoreCase(String.valueOf(location))) {
BufferedReader bufferedReader = new BufferedReader(new FileReader(String.valueOf(inputItemTransfer)));
FileWriter fileWriter = new FileWriter(inputTransferToLocation + ".txt", true);
BufferedWriter outputStream = new BufferedWriter(fileWriter);
String str;
while ((str = bufferedReader.readLine()) != null) {
outputStream.write(str + "\n");
}
outputStream.close();
}
}
}
}
}
}
I assume that I do something wrong with the scanner .
Any help/critics are totaly appreciated
You don't need to create a Scanner object for every prompt where the User needs to input data. One Scanner object for the entire application will do just fine. Just declare the object as public static within the Main class, for example:
public class Main extends Item {
// Declare a Scanner object that can potentially be used anywhere.
public static Scanner userInput = new Scanner(System.in).useDelimiter("\\R");
public Main(String location, Integer length, Integer height, Integer depth) {
super(location, length, height, depth);
}
public static void main(String[] args) throws IOException {
// ... main() method code here ...
}
}
Then everywhere you have a prompt to the User and need to use a Scanner method to get input, use Main.userInput. instead, for example:
user_choice = Main.userInput.nextInt();
or:
String itemName = Main.userInput.nextLine();
When using Scanner#nextInt() (or any Scanner#nextXXX methods) and a Scanner#nextLine() prompt will directly follow then you will most likely need to consume the newline character from when the enter key is hit from the Scanner#nextInt() use. The nextInt() method does not consume the newline character like the nextline() method does and therefore the prompt using the nextLine() method appears to be skipped. In cases like this you would want to do:
user_choice = Main.userInput.nextInt();
Main.userInput.nextLine();
A good rule of thumb is:
If you use the Scanner#nextLine() method, then use it for everything otherwise, don't use it at all. Use the next() and nextXXX() methods instead.
If you create your Scanner as shown above (with the useDelimiter("\\R") method) then the Scanner#next() method will return that similar to what the Scanner#nextLine() method would return.
Currently, your transferItemToLocation() method is double prompting for each prompt within the method because of the way you are using the Scanner methods.
public static void transferItemToLocation(List<Item> itemList, List<Location> locationList) throws IOException {
for (Item item : itemList) {
for (Location location : locationList) {
Scanner inputItemTransfer = new Scanner(System.in);
System.out.println("Insert the item you want to transfer + .txt extension!");
inputItemTransfer.nextLine();
if (inputItemTransfer.nextLine()
.equalsIgnoreCase(item + ".txt")) {
Scanner inputTransferToLocation = new Scanner(System.in);
System.out.println("Insert the location where you want to transfer the item");
inputTransferToLocation.nextLine();
if (inputTransferToLocation.nextLine()
.equalsIgnoreCase(String.valueOf(location))) {
BufferedReader bufferedReader = new BufferedReader(new FileReader(String.valueOf(inputItemTransfer)));
FileWriter fileWriter = new FileWriter(inputTransferToLocation + ".txt", true);
BufferedWriter outputStream = new BufferedWriter(fileWriter);
String str;
while ((str = bufferedReader.readLine()) != null) {
outputStream.write(str + "\n");
}
outputStream.close();
}
}
}
}
}
I can only assume why you are doing this because you have not provided all your code which is partially why I posted a lot of the drivel about Scanner above. What you've got here is not going to work the way you think it will. As mentioned earlier, get rid of all those Scanner objects and use something similar to what is declared within the Main class (similar to what is shown at the beginning of this post). Declare String variables named inputItemTransfer and inputTransferToLocation. Place the User input into those variables respectively for each prompt and use the data contained within those variables rather than the Scanner objects, for example:
public static void transferItemToLocation(List<Item> itemList, List<Location> locationList) throws IOException {
String inputItemTransfer;
String inputTransferToLocation;
for (Item item : itemList) {
for (Location location : locationList) {
System.out.println("Insert the item you want to transfer + .txt extension!");
inputItemTransfer = Main.userInput.nextLine();
if (inputItemTransfer.equalsIgnoreCase(item + ".txt")) {
System.out.println("Insert the location where you want to transfer the item");
inputTransferToLocation = Main.userInput.nextLine();
if (inputTransferToLocation.equalsIgnoreCase(String.valueOf(location))) {
BufferedReader bufferedReader = new BufferedReader(new FileReader(String.valueOf(inputItemTransfer)));
FileWriter fileWriter = new FileWriter(inputTransferToLocation + ".txt", true);
BufferedWriter outputStream = new BufferedWriter(fileWriter);
String str;
while ((str = bufferedReader.readLine()) != null) {
outputStream.write(str + "\n");
}
outputStream.close();
}
}
}
}
}
Whether this method is now going to function properly is honestly beyond me. Without all the code or at least a minimal reproducible example it's hard to say. One step at a time I suppose.
On a side:
As mentioned in Comments, it does indeed appear that there is a lot of required data entry by a User to utilize your application which is sort of a downer and actually difficult for some. Perhaps consider a more menu based system to reduce entry requirements and make usage a more comfortable experience.
Good luck.

FileNotFoundException When entering a string after input prompt

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.

output is null in the console

it's showing null exception. what to do now?
import java.io.File;
import java.util.Scanner;
public class Quiz1 {
public static void main(String[] args) {
File f = new File("QuizMark.txt");
try{
Scanner s = new Scanner (f);
QuizMark[] p = new QuizMark[10];
while(s.hasNext()==true)
{
int c = s.nextInt();
double d = s.nextInt();
for(int i=0;i<10;i++){
p[i]= new QuizMark(c,d);
System.out.println(p[i].getId());
System.out.println(p[i].getScore());
i++;
}
}
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
}
First of all your file must define a pattern of data saved in it like marks and id Separated by commas or hyphens underscores etc whatever you like to save pattern.Each next data should be on next line.Then read the text in proper manner as you saved in file.
Example QuizMarks.txt
01,96.5
02,78.9
03,65
04,89.7
Java Code
int count = 0;
String s[];
String line="";
QuizMark[] p = new QuizMark[10];
BufferedReader br= new BufferedReader(new FileReader("QuizMark.txt"));
while(line=br.readLine()!=null){
s=line.split(",");//your data separated by symbol in file
//First Record with id and marks
int id =Interger.parseInt(s[0]); //conversion from string to int
double marks = Double.parseDouble(s[1]); //conversion from string to double
p[count]= new QuizMark(id,marks);
count++;
}

Reading and modifying the text from the text file in Java

I am have a project that need to modify some text in the text file.
Like BB,BO,BR,BZ,CL,VE-BR
I need make it become BB,BO,BZ,CL,VE.
and HU, LT, LV, UA, PT-PT/AR become HU, LT, LV, UA,/AR.
I have tried to type some code, however the code fail to loop and also,in this case.
IN/CI, GH, KE, NA, NG, SH, ZW /EE, HU, LT, LV, UA,/AR, BB
"AR, BB,BO,BR,BZ,CL, CO, CR, CW, DM, DO,VE-AR-BR-MX"
I want to delete the AR in second row, but it just delete the AR in first row.
I got no idea and seeking for helps.
Please
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.Scanner;
public class tomy {
static StringBuffer stringBufferOfData = new StringBuffer();
static StringBuffer stringBufferOfData1 = stringBufferOfData;
static String filename = null;
static String input = null;
static String s = "-";
static Scanner sc = new Scanner(s);
public static void main(String[] args) {
boolean fileRead = readFile();
if (fileRead) {
replacement();
writeToFile();
}
System.exit(0);
}
private static boolean readFile() {
System.out.println("Please enter your files name and path i.e C:\\test.txt: ");
filename = "C:\\test.txt";
Scanner fileToRead = null;
try {
fileToRead = new Scanner(new File(filename));
for (String line; fileToRead.hasNextLine()
&& (line = fileToRead.nextLine()) != null;) {
System.out.println(line);
stringBufferOfData.append(line).append("\r\n");
}
fileToRead.close();
return true;
} catch (FileNotFoundException ex) {
System.out.println("The file " + filename + " could not be found! "+ ex.getMessage());
return false;
} finally {
fileToRead.close();
return true;
}
}
private static void writeToFile() {
try {
BufferedWriter bufwriter = new BufferedWriter(new FileWriter(
filename));
bufwriter.write(stringBufferOfData.toString());
bufwriter.close();
} catch (Exception e) {// if an exception occurs
System.out.println("Error occured while attempting to write to file: "+ e.getMessage());
}
}
private static void replacement() {
System.out.println("Please enter the contents of a line you would like to edit: ");
String lineToEdit = sc.nextLine();
int startIndex = stringBufferOfData.indexOf(lineToEdit);
int endIndex = startIndex + lineToEdit.length() + 2;
String getdata = stringBufferOfData.substring(startIndex + 1, endIndex);
String data = " ";
Scanner sc1 = new Scanner(getdata);
Scanner sc2 = new Scanner(data);
String lineToEdit1 = sc1.nextLine();
String replacementText1 = sc2.nextLine();
int startIndex1 = stringBufferOfData.indexOf(lineToEdit1);
int endIndex1 = startIndex1 + lineToEdit1.length() + 3;
boolean test = lineToEdit.contains(getdata);
boolean testh = lineToEdit.contains("-");
System.out.println(startIndex);
if (testh = true) {
stringBufferOfData.replace(startIndex, endIndex, replacementText1);
stringBufferOfData.replace(startIndex1, endIndex1 - 2,
replacementText1);
System.out.println("Here is the new edited text:\n"
+ stringBufferOfData);
} else {
System.out.println("nth" + stringBufferOfData);
System.out.println(getdata);
}
}
}
I wrote a quick method for you that I think does what you want, i.e. remove all occurrences of a token in a line, where that token is embedded in the line and is identified by a leading dash.
The method reads the file and writes it straight out to a file after editing for the token. This would allow you to process a huge file without worrying about about memory constraints.
You can simply rename the output file after a successful edit. I'll leave it up to you to work that out.
If you feel you really must use string buffers to do in memory management, then grab the logic for the line editing from my method and modify it to work with string buffers.
static void onePassReadEditWrite(final String inputFilePath, final String outputPath)
{
// the input file
Scanner inputScanner = null;
// output file
FileWriter outputWriter = null;
try
{
// open the input file
inputScanner = new Scanner(new File(inputFilePath));
// open output file
File outputFile = new File(outputPath);
outputFile.createNewFile();
outputWriter = new FileWriter(outputFile);
try
{
for (
String lineToEdit = inputScanner.nextLine();
/*
* NOTE: when this loop attempts to read beyond EOF it will throw the
* java.util.NoSuchElementException exception which is caught in the
* containing try/catch block.
*
* As such there is NO predicate required for this loop.
*/;
lineToEdit = inputScanner.nextLine()
)
// scan all lines from input file
{
System.out.println("START LINE [" + lineToEdit + "]");
// get position of dash in line
int dashInLinePosition = lineToEdit.indexOf('-');
while (dashInLinePosition != -1)
// this line has needs editing
{
// split line on dash
String halfLeft = lineToEdit.substring(0, dashInLinePosition);
String halfRight = lineToEdit.substring(dashInLinePosition + 1);
// get token after dash that is to be removed from whole line
String tokenToRemove = halfRight.substring(0, 2);
// reconstruct line from the 2 halves without the dash
StringBuilder sb = new StringBuilder(halfLeft);
sb.append(halfRight.substring(0));
lineToEdit = sb.toString();
// get position of first token in line
int tokenInLinePosition = lineToEdit.indexOf(tokenToRemove);
while (tokenInLinePosition != -1)
// do for all tokens in line
{
// split line around token to be removed
String partLeft = lineToEdit.substring(0, tokenInLinePosition);
String partRight = lineToEdit.substring(tokenInLinePosition + tokenToRemove.length());
if ((!partRight.isEmpty()) && (partRight.charAt(0) == ','))
// remove prefix comma from right part
{
partRight = partRight.substring(1);
}
// reconstruct line from the left and right parts
sb.setLength(0);
sb = new StringBuilder(partLeft);
sb.append(partRight);
lineToEdit = sb.toString();
// find next token to be removed from line
tokenInLinePosition = lineToEdit.indexOf(tokenToRemove);
}
// handle additional dashes in line
dashInLinePosition = lineToEdit.indexOf('-');
}
System.out.println("FINAL LINE [" + lineToEdit + "]");
// write line to output file
outputWriter.write(lineToEdit);
outputWriter.write("\r\n");
}
}
catch (java.util.NoSuchElementException e)
// end of scan
{
}
finally
// housekeeping
{
outputWriter.close();
inputScanner.close();
}
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
catch(IOException e)
{
inputScanner.close();
e.printStackTrace();
}
}

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.

Categories

Resources