Java Exception Handling with Try in a method - java

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 {
}

Related

Using formulas from a text/writing to a text

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;
}
}
}

Need to know how to copy lines of text to another file in Java for data formatting program

I would like some help with a project that I am working on. I want to create a simple program that formats data into a way that is accepting of our database. I am having trouble copying the contents of the main file to the destination file. The program creates the new destination file and it writes the "Gage ID, Date/Time, Precip_1min, Precip/Year" headers in the file but there are no data values copied to the new file. I have tried to look online for some solutions but, I have had no luck in applying these solutions. The main thing that I am concentrating on is copying each line of the main file to the new created file one-by-one then I will work from there. Any assistance is very much appreciated! Here is my code so far. P.S Cowlic105.txt is the file that has the lines of data that I want to be copied.
import java.io.*;
import java.util.Scanner;
public class MyDataFormat {
public static void main(String[] args) {
String fileName = "Cowlic105.txt";
String fileName2 = "FormDatFile.txt";
String line = null;
int x;
int gageID;
int precipYTD;
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println("Unable to open file '" + fileName + "'");
}
catch(IOException ex) {
System.out.println("Error reading file '" + fileName + "'");
}
Scanner in = new Scanner(System.in);
System.out.println("Is this the file you wish to format? " + fileName + "(0 for no, 1 for yes)");
x = in.nextInt();
if (x == 0){
System.exit(0);
}
else if (x == 1){
System.out.println("Hello there you resumed the program!!!");
System.out.println("What is the ID of the rain gage? ");
gageID = in.nextInt();
System.out.println("What is the value of precipitation YTD? ");
precipYTD = in.nextInt();
File destFile = new File("FormDatFile.txt");
if(!destFile.exists()){
try {
destFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
FileInputStream fis = new FileInputStream(destFile);
FileWriter writer = new FileWriter(destFile, true);
BufferedWriter write2 = new BufferedWriter(writer);
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis));
while((line = bufferedReader.readLine()) != null){
write2.write(line);
write2.newLine();
bufferedReader.close();
write2.close();
}
writer.write("Gage ID,Date/Time,Precip_1min,Precip/Year");
writer.write("\r\n");
writer.close();
}
catch (IOException e){
e.printStackTrace();
}
}
}
}

Debugging File Search / Merge Code

This program is meant to see two files located in a particular folder and then merge those two files and create a third file which is does. From the third merged file it is then searching for a keyword such as "test", once it finds that key word it prints out the location and the line of the keyword which is what is somewhat doing. What is happening is when I run the program it stops after the finds the keyword the first time in a line but it will not continue to search that line. So if there is multiple keyword 'test' in the line it will only find the first one and spit back the position and line. I want it to print both or multiple keywords. I think it is because of the IndexOf logic which is causing the issue.
import com.sun.deploy.util.StringUtils;
import java.io.*;
import java.lang.*;
import java.util.Scanner;
public class Concatenate {
public static void main(String[] args) {
String sourceFile1Path = "C:/Users/me/Desktop/test1.txt";
String sourceFile2Path = "C:/Users/me/Desktop/test2.txt";
String mergedFilePath = "C:/Users/me/Desktop/merged.txt";
File[] files = new File[2];
files[0] = new File(sourceFile1Path);
files[1] = new File(sourceFile2Path);
File mergedFile = new File(mergedFilePath);
mergeFiles(files, mergedFile);
stringSearch(args);
}
private static void mergeFiles(File[] files, File mergedFile) {
FileWriter fstream = null;
BufferedWriter out = null;
try {
fstream = new FileWriter(mergedFile, true);
out = new BufferedWriter(fstream);
} catch (IOException e1) {
e1.printStackTrace();
}
for (File f : files) {
System.out.println("merging: " + f.getName());
FileInputStream fis;
try {
fis = new FileInputStream(f);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
String aLine;
while ((aLine = in.readLine()) != null) {
out.write(aLine);
out.newLine();
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void stringSearch(String args[]) {
try {
String stringSearch = "test";
BufferedReader bf = new BufferedReader(new FileReader("C:/Users/me/Desktop/merged.txt"));
int linecount = 0;
String line;
System.out.println("Searching for " + stringSearch + " in file");
while (( line = bf.readLine()) != null){
linecount++;
int indexfound = line.indexOf(stringSearch);
if (indexfound > -1) {
System.out.println(stringSearch + " was found at position " + indexfound + " on line " + linecount);
System.out.println(line);
}
}
bf.close();
}
catch (IOException e) {
System.out.println("IO Error Occurred: " + e.toString());
}
}
}
It's because you are searching for the word once per line in your while loop. Each iteration of the loop takes you to the next line of the file because you are calling bf.readLine(). Try something like the following. You may have to tweak it but this should get you close.
while (( line = bf.readLine()) != null){
linecount++;
int indexfound = line.indexOf(stringSearch);
while(indexfound > -1)
{
System.out.println(stringSearch + " was found at position " + indexfound + " on line " + linecount);
System.out.println(line);
indexfound = line.indexOf(stringSearch, indexfound);
}
}

Trying to Read text line by line and write into output file each line in Java

I am trying to read data from a text file (line by line) and I want to write into output file the lines I read from the flies.
Here is how I programmed my code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class read {
public static void main(String args[])
{
String input = null;
input = readFile();
writeFile(input);
}
public static void writeFile(String in)
{
String fileName = "output.txt";
//String payload = null;
try {
FileWriter fw = new FileWriter(fileName);
BufferedWriter bw =new BufferedWriter(fw);
bw.write(in);
System.out.println("Received "+in.length()+" bytes: ");
bw.close();
}
catch(IOException ex) {
System.out.println("Error writing to file '"+ fileName + "'");
}
}
public static String readFile()
{
String fileName = "temp.txt";
String line = null;
String Sentence = null;
try {
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
while((line = br.readLine()) != null) {
//Sentence += line+'\n';
Sentence = line +'\n';
}
br.close();
System.out.println("Sending file "+fileName);
return Sentence;
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
return null;
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
return null;
// Or we could just do this:
// ex.printStackTrace();
}
}
}
text file:
I returned##% from the City about three o'clock on that
May afternoon pretty well disgusted with life.
I had been three months in the Old Country, and was
fed up with it.
Output:
The read method reads first line from the text file and writes that line into output file...
I am new in programming and would really appreciate help!
For creating the output file, try this:
PrintWriter writer = new PrintWriter(filename, "UTF-8");
writer.println(in);
writer.close();
When you read from the file you should append the lines to your original variables by doing
Sentence += line+'\n';

How to update a file content in Java

First, I output the content of the file, here is my code. And then, I will do some string work to edit each line. What if I what to save the changes, how to do it? Can I do it without creating a tmp file?
String executeThis = "cat" + " " + "/var/lib/iscsi/nodes/"
+ iscsiInfo.selectedTargets2.get(i) + "/" + myString + "/default";
String inputThis = "";
Process process = ServerHelper.callProcessWithInput(executeThis, inputThis);
try {
logger.debug("stdOutput for editing targets credential:");
BufferedReader stdOutput = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String s = null;
while ((s = stdOutput.readLine()) != null) {
logger.info("The content is########################"+s)
// do something to edit each line and update the file
}
} catch (IOException e) {
logger.fatal(e);
}
The following steps could achieve what you are looking for.
Instantiate a FileWriter object to create a tmp file.
FileWriter fw = new FileWriter("tmp");
Read line by line from the source file.
Modify this line (string object) in memory.
Write out this string in the tmp file.
fw.write(line);
Close the file handles.
Rename the tmp file to the source file name.
sourceFile.renameTo(targetFile);
This question has been answered here. I repeat the answer.
public static void replaceSelected(String replaceWith, String type) {
try {
// input the file content to the String "input"
BufferedReader file = new BufferedReader(new FileReader("notes.txt"));
String line;String input = "";
while ((line = file.readLine()) != null) input += line + '\n';
System.out.println(input); // check that it's inputted right
// this if structure determines whether or not to replace "0" or "1"
if (Integer.parseInt(type) == 0) {
input = input.replace(replaceWith + "1", replaceWith + "0");
}
else if (Integer.parseInt(type) == 1) {
input = input.replace(replaceWith + "0", replaceWith + "1");
}
// check if the new input is right
System.out.println("----------------------------------" + '\n' + input);
// write the new String with the replaced line OVER the same file
FileOutputStream File = new FileOutputStream("notes.txt");
File.write(input.getBytes());
} catch (Exception e) {
System.out.println("Problem reading file.");
}
}
public static void main(String[] args) {
replaceSelected("Do the dishes","1");
}

Categories