Using formulas from a text/writing to a text - java

So, my lecture powerpoint slides and even my book is not really doing a good job (for my understanding that is) of explaining how to use formulas from a text document, then when the code runs/compiles successfully it will create a "Results.txt" in the same folder.
These are the formulas in a notepad doc. Nothing to crazy, just a proof of concept
4 * 5 ..
3 / 4...
3 - 1..
2 + 3..
import java.io.*;
import java.util.*;
public class ReadFileLineByLine {
public static void main(String[] args) throws FileNotFoundException {
String line;
int numberOfLines = 3;
String[] textData = new String[numberOfLines];
int i;
for(i = 0; i < numberOfLines; i++){
textData[i] = textReader.readLine();
}
text.Reader.close();
return textData;
try {
File inputfile = new File(args[0]); //new File("formulas.txt")
Scanner input = new Scanner(new File("C:\Users\Frost\Documents\Question4"));
BuffredReader br = new BufferedReader(new FileReader("C:\Users\Frost\Documents\Question4"));
PrintWriter output = new PrintWriter("Results.txt");
while (input.hasNextLine()) {
line = input.nextLine();
System.out.println("read <" + line + ">"); // Display message to commandline
// Declare ArrayList of for storing tokenized formula from String line
double result = 0; // The variable to store result of the operation
// Determine the operator and calculate value of the result
System.out.println(formula.get(0) + ' ' + formula.get(1) + ' ' +
formula.get(2) + " = " + result); // Display result to command line
// Write result to file
}
// Need to close input and output files
}
catch (FileNotFoundException e) {
System.out.println("Error reading file named " + Formulas.txt);
}
}
}

Here's something to get you started. The //TODO: comments are where you need to build your logic. Be sure to change the file paths back to what you need. I changed them to a Temp location. Also change the messages printed as I just put something there as proof of concept. I tried to comment thoroughly but don't hesitate to ask questions.
import java.io.*;
import java.util.*;
public class ReadFileLineByLine {
public static void main(String[] args) throws FileNotFoundException {
String line = "";
//Declare Scanner and PrintWriter outside of try clause so they can be closed in finally clause
Scanner input = null;
PrintWriter output = null;
try {
//Instantiate input and output file
input = new Scanner(new File("C:\\Temp\\test.txt"));
output = new PrintWriter(new File("C:\\Temp\\Results.txt"));
//Loop through lines in input file
while (input.hasNextLine()) {
line = input.nextLine();
// Display message to commandline
System.out.println("read <" + line + ">");
// Populate ArrayList of tokenized formula from String line
//TODO:
// The variable to store result of the operation
double result = 0;
// Determine the operator and calculate value of the result
//TODO:
// Write result to file
output.println("Print result of " + line + " to Results.txt");
}
} catch (FileNotFoundException e) {
//Exception thrown, print message to console
System.out.println("File Not Found: " + e.getMessage());
} finally {
//close files in finally clause so it happens even if exception is thrown
//I also set to null as extra precaution
input.close();
input = null;
output.close();
output = null;
}
}
}

Related

Storing data into a file for one time and avoid any changes after running the code again

My code
Here I take a name from a user and save it to a file, my purpose is to give that name an index (Out) and save it into a file, so that each time I run the code, I will still have the same name and index(not new values). So how can I do that?
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class h_main {
public static void main(String[] args) {
contact[] table = new contact[3]; //Create an object of contact class
int tablesize = 3;
// Input from user
//**Inserting from user**//
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a name: ");
String names = reader.nextLine();
// Save the inserted name inside a table array with an index Out(from the hash function)
int Out = calc_hash(names, tablesize);
table[Out] = new contact();
table[Out].Name = names;
System.out.println(Out);
// Writing
for (int i = 0; i < table.length; i++) {
FileWriter fWriter = null;
BufferedWriter writer = null;
try {
fWriter = new FileWriter("text.txt");
writer = new BufferedWriter(fWriter);
writer.write(table[i].Name);
writer.write(table[i].phone);
writer.newLine();
writer.close();
}
// System.err.println("Your input of " + table[i].Name.length + " characters was saved.");
catch (Exception e) {
System.out.println("Error!");
}
// Reading
// The name of the file to open.
String fileName = "text.txt";
// This will reference one line at a time
String line = null;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader("text.txt");
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
System.out.println("Name: " + line);
}
// Always close files.
bufferedReader.close();
} catch (FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
"text.txt" + "'");
} catch (IOException ex) {
System.out.println(
"Error reading file '" +
"text.txt" + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
//**Generate hash function**//
public static int calc_hash(String names, int table_size) {
int i, l = names.length();
int hash = 0;
for (i = 0; i < l; i++) {
hash += Character.getNumericValue(names.charAt(i));
hash += (hash << 10);
hash ^= (hash >> 6);
}
hash += (hash << 3);
hash ^= (hash >> 11);
hash += (hash << 15);
if (hash > 0) return hash % table_size;
else return -hash % table_size;
}
}
Class contact
public class contact {
String Name ;
int phone ;
}
Have the file not exist when you run the program for the first time. After you do, use the existence of the file to determine whether the program has been run before or not. Your code could look like this:
import java.nio.file.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
// It's recommended to follow Java naming and style conventions:
// Class names always begin with an uppercase letter
Contact[] table = new Contact[3];
String fileName = "text.txt";
Path file = Paths.get(fileName);
// Check for persistence file:
if(Files.exists(file)) {
// If all you need to do is print each line, try this:
try {
Files.lines(file).forEach(l -> System.out.println("Name: " + l));
} catch(IOException e) {
System.err.println("Error reading data file!");
}
} else {
// Take data input
Scanner scanner = new Scanner(System.in);
// ...
// When program is terminated, save everything:
try(BufferedWriter writer = Files.newBufferedWriter(file)) {
// use writer to write data...
} catch(IOException e) {
System.err.println("Error writing data file!");
}
}
}
}

Storing an array of strings without initializing the size

Background: This program reads in a text file and replaces a word in the file with user input.
Problem: I am trying to read in a line of text from a text file and store the words into an array.
Right now the array size is hard-coded with an number of indexes for test purposes, but I want to make the array capable of reading in a text file of any size instead.
Here is my code.
public class FTR {
public static Scanner input = new Scanner(System.in);
public static Scanner input2 = new Scanner(System.in);
public static String fileName = "C:\\Users\\...";
public static String userInput, userInput2;
public static StringTokenizer line;
public static String array_of_words[] = new String[19]; //hard-coded
/* main */
public static void main(String[] args) {
readFile(fileName);
wordSearch(fileName);
replace(fileName);
}//main
/*
* method: readFile
*/
public static void readFile(String fileName) {
try {
FileReader file = new FileReader(fileName);
BufferedReader read = new BufferedReader(file);
String line_of_text = read.readLine();
while (line_of_text != null) {
System.out.println(line_of_text);
line_of_text = read.readLine();
}
} catch (Exception e) {
System.out.println("Unable to read file: " + fileName);
System.exit(0);
}
System.out.println("**************************************************");
}
/*
* method: wordSearch
*/
public static void wordSearch(String fileName) {
int amount = 0;
System.out.println("What word do you want to find?");
userInput = input.nextLine();
try {
FileReader file = new FileReader(fileName);
BufferedReader read = new BufferedReader(file);
String line_of_text = read.readLine();
while (line_of_text != null) { //there is a line to read
System.out.println(line_of_text);
line = new StringTokenizer(line_of_text); //tokenize the line into words
while (line.hasMoreTokens()) { //check if line has more words
String word = line.nextToken(); //get the word
if (userInput.equalsIgnoreCase(word)) {
amount += 1; //count the word
}
}
line_of_text = read.readLine(); //read the next line
}
} catch (Exception e) {
System.out.println("Unable to read file: " + fileName);
System.exit(0);
}
if (amount == 0) { //if userInput was not found in the file
System.out.println("'" + userInput + "'" + " was not found.");
System.exit(0);
}
System.out.println("Search for word: " + userInput);
System.out.println("Found: " + amount);
}//wordSearch
/*
* method: replace
*/
public static void replace(String fileName) {
int amount = 0;
int i = 0;
System.out.println("What word do you want to replace?");
userInput2 = input2.nextLine();
System.out.println("Replace all " + "'" + userInput2 + "'" + " with " + "'" + userInput + "'");
try {
FileReader file = new FileReader(fileName);
BufferedReader read = new BufferedReader(file);
String line_of_text = read.readLine();
while (line_of_text != null) { //there is a line to read
line = new StringTokenizer(line_of_text); //tokenize the line into words
while (line.hasMoreTokens()) { //check if line has more words
String word = line.nextToken(); //get the word
if (userInput2.equalsIgnoreCase(word)) {
amount += 1; //count the word
word = userInput;
}
array_of_words[i] = word; //add word to index in array
System.out.println("WORD: " + word + " was stored in array[" + i + "]");
i++; //increment array index
}
//THIS IS WHERE THE PRINTING HAPPENS
System.out.println("ARRAY ELEMENTS: " + Arrays.toString(array_of_words));
line_of_text = read.readLine(); //read the next line
}
BufferedWriter outputWriter = null;
outputWriter = new BufferedWriter(new FileWriter("C:\\Users\\..."));
for (i = 0; i < array_of_words.length; i++) { //go through the array
outputWriter.write(array_of_words[i] + " "); //write word from array to file
}
outputWriter.flush();
outputWriter.close();
} catch (Exception e) {
System.out.println("Unable to read file: " + fileName);
System.exit(0);
}
if (amount == 0) { //if userInput was not found in the file
System.out.println("'" + userInput2 + "'" + " was not found.");
System.exit(0);
}
}//replace
}//FTR
You can use java.util.ArrayList (which dynamically grows unlike an array with fixed size) to store the string objects (test file lines) by replacing your array with the below code:
public static List<String> array_of_words = new java.util.ArrayList<>();
You need to use add(string) to add a line (string) and get(index) to retrieve the line (string)
Please refer the below link for more details:
http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html
You may want to give a try to ArrayList.
In Java normal arrays cannot be initialized without giving initial size and they cannot be expanded during run time. Whereas ArrayLists have resizable-array implementation of the List interface.ArrayList also comes with number of useful builtin functions such as
Size()
isEmpty()
contains()
clone()
and others. On top of these you can always convert your ArrayList to simple array using ArrayList function toArray(). Hope this answers your question. I'll prepare some code and share with you to further explain things you can achieve using List interface.
Use not native [] arrays but any kind of java collections
List<String> fileContent = Files.readAllLines(Paths.get(fileName));
fileContent.stream().forEach(System.out::println);
long amount = fileContent.stream()
.flatMap(line -> Arrays.stream(line.split(" +")))
.filter(word -> word.equalsIgnoreCase(userInput))
.count();
List<String> words = fileContent.stream()
.flatMap(line -> Arrays.stream(line.split(" +")))
.filter(word -> word.length() > 0)
.map(word -> word.equalsIgnoreCase(userInput) ? userInput2 : word)
.collect(Collectors.toList());
Files.write(Paths.get(fileName), String.join(" ", words).getBytes());
of course you can works with such lists more traditionally, with loops
for(String line: fileContent) {
...
}
or even
for (int i = 0; i < fileContent.size(); ++i) {
String line = fileContent.get(i);
...
}
i just like streams :)

How can I print the average of the lines in this file?

I'm writing a program in Java which iterates over each line of a text file, this text file contains numbers which are on a separate line, I have successfully made the program read each line and print them to a new file.
However I'm trying to print the average of these numbers to the new file as well, I understand that I would have to treat each line as a float or double (as I'm using decimal numbers) but I'm unsure of how to do this, this is what I've got so far.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
public class Run {
public static void main(String[] args) throws Exception {
Write(); //call Write method
}
public static void Write() throws Exception {
String line, lineCut;
BufferedReader br = null; //initialise BR- reads text from file
BufferedWriter bw = null; //initialise BR- writes text to file
try
{
br = new BufferedReader(new FileReader("/Users/jbloggs/Documents/input.txt")); //input file
bw = new BufferedWriter(new FileWriter("/Users/jbloggs/Desktop/output.txt")); //output file
line = br.readLine(); // declare string equal to each line
while(line != null) { // iterate over each line
lineCut = line.replaceAll(";" , ","); // replace ; with ,
//lineCut = line.substring(1, line.length());
//int mynewLine = Integer.parseInt(lineCut);
bw.write(lineCut); // write each line to output file
bw.write("\n"); // print each line on a new line
line = br.readLine();
}
System.out.println("success"); //print if program works
br.close();
bw.close();
}
catch(Exception e){
throw(e); // throw exception
}
}
}
Basically this is what you are doing
reading lines from a file
replacing ';' with a ','
writing this modified line to a new file
So in each of above operation, you have never treated the line to be a Number. To find average, you need to parse each line of number into real Number, Double.parseDouble("21.2") etc, and in each iteration, you know what to do :-)
For example:
double sum= 0;
int count = 0;
while(line != null) { // iterate over each line
lineCut = line.replaceAll(";" , ","); // replace ; with ,
//lineCut = line.substring(1, line.length());
int num = Double.parseDouble(lineCut);
sum = sum + num; count++;
bw.write(lineCut); // write each line to output file
bw.write("\n"); // print each line on a new line
line = br.readLine();
}
br.write(String.valueOf(sum/count));
Not tested. I am considering each line has a number and nothing else. Remember your should check the valou on linecount to avoid an Exception during the conversion from String to float.
public static void Write() throws Exception {
String line, lineCut;
BufferedReader br = null; //initialise BR- reads text from file
BufferedWriter bw = null; //initialise BR- writes text to file
try
{
br = new BufferedReader(new FileReader("/Users/jbloggs/Documents/input.txt")); //input file
bw = new BufferedWriter(new FileWriter("/Users/jbloggs/Desktop/output.txt")); //output file
line = br.readLine(); // declare string equal to each line
float sum = 0;
int counter = 0;
while(line != null) { // iterate over each line
lineCut = line.replaceAll(";" , ",");
sum += Float.parseFloat(lineCut);
counter++;
bw.write(lineCut); // write each line to output file
bw.write("\n"); // print each line on a new line
line = br.readLine();
}
bw.write("Average = ");
bw.write(sum / counter);
bw.write("\n");
System.out.println("success"); //print if program works
br.close();
bw.close();
}
catch(Exception e){
throw(e); // throw exception
}
}
}

Java Exception Handling with Try in a method

I am trying to design two different methods for a Java application. The first method will pass in a string of the name of a file, and return the text of a text file as a string. The second method will pass in the name of a file and the text, and create a new text file and output the string into the file.
Currently my code works without the methods, but I am trying to design it with a separation of concerns and low coupling. I am trying to modify it so I can just call a method to output any sort of data I have in a string to a text file.
Here is my code without the methods:
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class FileCopier {
public static void main(String[] args) {
//What file should be input for reading?
String inputFile = askForInput("Please enter the name of the file to be read in: ");
//What file should be created to display output ?
String outputFile = askForInput("Please come up with a name of the file to be written backwards: ");
//Check to make sure we got the names
System.out.println("inputFile: " + inputFile + " outputFile: " + outputFile);
// Variables to read and write the files
//Call the readTextFile method to read text file into string data
String line = null;
String total = null;
BufferedReader input = null;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(inputFile);
// Always wrap FileReader in BufferedReader.
input = new BufferedReader(fileReader);
total = input.readLine() + "\n";
while ((line = input.readLine()) != null && total != null) {
total += line + "\n";
System.out.println("Proof that the file says: " + line);
}
input.close();
//Check to make sure we got the text files data
System.out.println("The total string says: \n" + total);
//Call the reverseWords method to switch 'Hello' with 'World'
String info = reverseWords(total);
//Check to make sure the string was reversed
System.out.println("The reversed string says: \n" + info);
File file = new File(outputFile);
BufferedWriter output = null;
output = new BufferedWriter(new FileWriter(file));
output.write(info);
System.out.println("The output file: " + outputFile + " has been written.");
output.close();
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '" +
inputFile + "'");
} catch (IOException ex) {
System.out.println("Error reading file '" + inputFile + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
public static String reverseWords(String sentence) {
String[] parts = sentence.trim().split("\\s+");
StringBuilder builder = new StringBuilder();
builder.append(parts[parts.length - 1]);
for (int i = parts.length - 2; i >= 0; --i) {
builder.append(" ").append(parts[i]);
}
return builder.toString();
}
public static String askForInput(String question) {
System.out.println(question);
Scanner in = new Scanner(System.in);
String inputFile = in.nextLine();
return inputFile;
}
}
When creating a method for each of the "read" and "write" portions of my code, I constantly get errors that I assume are from the exception handling. Any thoughts on how to separate code that has exceptions involved?
Think in terms of single responsibility. You have two distinct operations that need to happen: reading and writing.
Let's start with reading. What you're doing right now to read the file surmises these lines:
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(inputFile);
// Always wrap FileReader in BufferedReader.
input = new BufferedReader(fileReader);
total = input.readLine() + "\n";
while ((line = input.readLine()) != null && total != null) {
total += line + "\n";
System.out.println("Proof that the file says: " + line);
}
input.close();
Move that to a method.
private static String readFile(String inputFile) throws IOException {
BufferedReader input;
String total;
String line;// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(inputFile);
// Always wrap FileReader in BufferedReader.
input = new BufferedReader(fileReader);
total = input.readLine() + "\n";
while ((line = input.readLine()) != null) {
total += line + "\n";
System.out.println("Proof that the file says: " + line);
}
input.close();
return total;
}
Here's what we did:
We have a variable total which is used elsewhere in the program, so that usage has to be preserved. We're returning String and will declare total = readFile(inputFile); on the outside.
We've changed nothing. This code will run the same way as it did without the method.
Now, if we want to move the writing functionality, which is:
File file = new File(outputFile);
BufferedWriter output = null;
output = new BufferedWriter(new FileWriter(file));
output.write(info);
System.out.println("The output file: " + outputFile + " has been written.");
output.close();
...we just do.
private static void writeFile(String outputFile, String info) throws IOException {
File file = new File(outputFile);
BufferedWriter output = null;
output = new BufferedWriter(new FileWriter(file));
output.write(info);
System.out.println("The output file: " + outputFile + " has been written.");
output.close();
}
Again, nothing's changed on this method. We don't have any other usages of any of the variables in here to worry about, so we can directly bring it across.
All said, that try block looks a bit anemic:
try {
total = readFile(inputFile);
//Check to make sure we got the text files data
System.out.println("The total string says: \n" + total);
//Call the reverseWords method to switch 'Hello' with 'World'
String info = reverseWords(total);
//Check to make sure the string was reversed
System.out.println("The reversed string says: \n" + info);
writeFile(outputFile, info);
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '" +
inputFile + "'");
} catch (IOException ex) {
System.out.println("Error reading file '" + inputFile + "'");
// Or we could just do this:
// ex.printStackTrace();
}
...which is a good thing.
I am not sure what are you asking about but try to create your own Exceptions and make your methods throw them like this
package com.qmic.test;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class FileCopier {
public static void main(String[] args) {
// What file should be input for reading?
String inputFile = askForInput("Please enter the name of the file to be read in: ");
// What file should be created to display output ?
String outputFile = askForInput("Please come up with a name of the file to be written backwards: ");
// Check to make sure we got the names
System.out.println("inputFile: " + inputFile + " outputFile: "
+ outputFile);
// Variables to read and write the files
// Call the readTextFile method to read text file into string data
String line = null;
String total = null;
BufferedReader input = null;
try {
String readData = readFileContents(inputFile);
// Check to make sure we got the text files data
System.out.println("The total string says: \n" + readData);
// Call the reverseWords method to switch 'Hello' with 'World'
String reversedContents = reverseWords(readData);
writeToFile(outputFile, reversedContents);
} catch (ReadException ex) {
System.out.println("Error reading file '" + inputFile + "'");
// Or we could just do this:
// ex.printStackTrace();
} catch (WriteException ex) {
System.out.println("Error Writing file '" + outputFile + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
public static String reverseWords(String sentence) {
String[] parts = sentence.trim().split("\\s+");
StringBuilder builder = new StringBuilder();
builder.append(parts[parts.length - 1]);
for (int i = parts.length - 2; i >= 0; --i) {
builder.append(" ").append(parts[i]);
}
return builder.toString();
}
public static String askForInput(String question) {
System.out.println(question);
Scanner in = new Scanner(System.in);
String inputFile = in.nextLine();
return inputFile;
}
public static void writeToFile(String fileName, String data)
throws WriteException {
BufferedWriter output = null;
try {
// Check to make sure the string was reversed
System.out.println("The reversed string says: \n" + data);
File file = new File(fileName);
output = new BufferedWriter(new FileWriter(file));
output.write(data);
System.out.println("The output file: " + fileName
+ " has been written.");
}catch(IOException e){
throw new WriteException();
}finally{
try {
output.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static String readFileContents(String fileName) throws ReadException {
// FileReader reads text files in the default encoding.
BufferedReader input = null;
String line = null;
String total = null;
try {
FileReader fileReader = new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
input = new BufferedReader(fileReader);
total = input.readLine() + "\n";
while ((line = input.readLine()) != null && total != null) {
total += line + "\n";
System.out.println("Proof that the file says: " + line);
}
} catch (IOException e) {
throw new ReadException();
}finally{
//This is ugly code, if you are using java 7 you have extra option to better this
try {
input.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return total;
}
}
//make me public and move me to a separate file
class WriteException extends IOException {
}
//make me public and move me to a separate file
class ReadException extends IOException {
}

Two problems with this java code, one fatal one not as fatal what are they?

Here is my code. This was a program I made for an interview, I was told the code had one fatal flaw, and one smaller problem. I could not find either. What is wrong with the program? I've tested it and it seems to work fine. I know the fileExists() method is kind of bad and need to do more checks... But other than that I am not sure what else could be wrong...
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
//I chose to use this library since it offers a solution to performing operations on CSV files, better than one I can provide from scratch.
import au.com.bytecode.opencsv.CSVReader;
public class csv2xml {
//Main program loop
public static void main(String[] args) {
String csvFilename;
String xmlFilename;
ArrayList<ArrayList<String>> data; //Raw unformatted data
boolean exists;
String xml; //Formated XML data
do{
System.out.println("Enter file path: ");
csvFilename = getUserInput(); //Gets filename from user
exists = fileExists(csvFilename);
if(exists){ //Checks to see if file exists
data = readFile(csvFilename); //Reads in content from CSV file
xml = toXML(data);
xmlFilename = csvFilename.split("\\.")[0]+".xml"; //Gets part of the filename before the first .
writeToFile(xml,xmlFilename);
}
else
System.out.println("Invalid file name, use full file path.");
}while(!exists);
}
//Reads a line of input from the user
//Returns: String
public static String getUserInput(){
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
return input;
}
//Checks to see if the file exists
//Arguments: String (name of file)
//Returns Boolean, true if file exists, false if it does not exist.
public static boolean fileExists(String filename){
File file = new File(filename);
if (file.exists()){
System.out.println("File exists");
return true;
}
return false;
}
//Reads content of CSV file and returns all data in a 2D array list
//Arguments: String (file name)
//Returns: ArrayList<ArrayList<String>> (A 2D arraylist containing the data from the csv file in a table format)
public static ArrayList<ArrayList<String>> readFile(String filename){
ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
ArrayList<String> currentRow;
CSVReader reader = null;
try {
reader = new CSVReader(new FileReader(filename));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String [] nextLine = null; // nextLine[] is an array of values in the current line
try {
while ((nextLine = reader.readNext()) != null) {
currentRow = new ArrayList<String>();
for(String s: nextLine){ //Puts data into a row in an arraylist
currentRow.add(s);
}
data.add(currentRow); //Adds row into arraylist
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return data;
}
//Inserts xml tags between the data segments,rows and columns
//Arguments: ArrayList<ArrayList<String>> (csv data)
//Returns: String (data with xml tags)
public static String toXML(ArrayList<ArrayList<String>> data){
String xml = "<?xml version= \"1.0\"?>";
for(int i = 0; i < data.size(); i++){
xml += "\n<row id=\""+i+"\">\n";
for(int z = 0; z < data.get(i).size(); z++){
xml += "<column id=\""+z+"\">\n";
xml += "\t<data>";
xml += data.get(i).get(z);
xml += "</data>";
xml += "\n</column>\n";
}
xml += "</row>";
}
return xml;
}
//Writes data in the filename specified
//Arguments: String (data to write), String (filename to write data to)
public static void writeToFile(String data,String filename){
try {
String fn = filename;
File file = new File(filename);
// if file doesnt exists, then create it
if (file.exists()) {
System.out.println("File already exists, overwrite?(y/n):");
if(getUserInput().toLowerCase().equals("n")){
do{
System.out.println("Enter new file name:");
filename = getUserInput()+".xml";
file = new File(filename);
}while(!isValidName(filename));
}
}
else{
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(data);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
//Check files name to make sure it is valid (found in MSDN Documentation)
//Arguments: String (filename)
//Returns: Boolean (true if filename is valid false if invalid)
public static boolean isValidName(String text)
{
Pattern pattern = Pattern.compile(
"# Match a valid Windows filename (unspecified file system). \n" +
"^ # Anchor to start of string. \n" +
"(?! # Assert filename is not: CON, PRN, \n" +
" (?: # AUX, NUL, COM1, COM2, COM3, COM4, \n" +
" CON|PRN|AUX|NUL| # COM5, COM6, COM7, COM8, COM9, \n" +
" COM[1-9]|LPT[1-9] # LPT1, LPT2, LPT3, LPT4, LPT5, \n" +
" ) # LPT6, LPT7, LPT8, and LPT9... \n" +
" (?:\\.[^.]*)? # followed by optional extension \n" +
" $ # and end of string \n" +
") # End negative lookahead assertion. \n" +
"[^<>:\"/\\\\|?*\\x00-\\x1F]* # Zero or more valid filename chars.\n" +
"[^<>:\"/\\\\|?*\\x00-\\x1F\\ .] # Last char is not a space or dot. \n" +
"$ # Anchor to end of string. ",
Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.COMMENTS);
Matcher matcher = pattern.matcher(text);
boolean isMatch = matcher.matches();
return isMatch;
}
}
Here is what I guess :
CSVReader reader = null;
try {
reader = new CSVReader(new FileReader(filename));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String [] nextLine = null; // nextLine[] is an array of values in the current line
try {
while ((nextLine = reader.readNext()) != null) {
currentRow = new ArrayList<String>();
for(String s: nextLine){ //Puts data into a row in an arraylist
currentRow.add(s);
}
data.add(currentRow); //Adds row into arraylist
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
So what happens if you do not initialize CSVreader ? The next block will throw a NullPointer Exception. You are not catching that one.
Also you are reading manually line by line when you can you simply use the library function.

Categories