Java: Confused with these file I/O methods not functioning - java

I'm trying to implement a method to write an array of Song() objects to a file for an assignment. I've become fairly lost on how to achieve this. I want to be able to call the function in the main method but it doesn't appear to do anything. At this stage it is a test where I want it to print on the command line upon running main().
Here's my code:
public static void main (String[] args)
{ //run the main program.
Interface songUI = new Interface();
songUI.run();
try{
PrintWriter outputTest = null;
outputTest = write("testfile");
read();
}
catch(IOException e){
System.out.println("Caught!");
}
}
public static PrintWriter write (String fileName) throws IOException{
Scanner console = new Scanner(System.in);
PrintWriter outFile = new PrintWriter(fileName);
outFile.println ("Random numbers");
for(int i=0; i<10; i++)
{
outFile.println ((int)( 1 + Math.random()*10) + " ");
}
outFile.close();
return outFile;
}
I also have a method for reading from the file i'm trying to get working here:
public static void read() throws IOException{
String fileName = "test1";
System.out.println ("The file " + fileName + "\ncontains the following lines:\n");
Scanner inputStream = new Scanner (new File (fileName));
while (inputStream.hasNextLine ())
{
String line = inputStream.nextLine ();
System.out.println (line);
}
inputStream.close ();
}
As you can tell i'm confused, and any help would be amazing. Thank you.

You are writing to testfile but trying to read from test1.
The code is poorly organized.
a method called write() shouldn't do anything else, and it should certainly not do input
returning a closed PrintWriter is completely pointless.
the write() method catches IOException internally, which makes it impossible for the caller to know about failure. Have it throw IOException instead, like the read() method does, and let the caller deal with it.

Related

Getting FileNotFoundException when trying to run a java program through CMD using input and output files

When I try to run this code through eclipse, it works fine, but when I try to run it through CMD using "java MainClass >result.txt" I get a FileNotFoundException.
This is the code in question:
import java.io.;
import java.util.;
public class MainClass
{
static int cellNumber;
static int freeSpace;
static int randomResult;
static int chosen;
static int choiceSize;
public static void main(String[] args)
{
Scanner in = null;
try
{
in = new Scanner(new FileReader("C:\\users\\Alon\\workspace\\ex2temp\\bin\\input.txt"));
FileWriter fw = new FileWriter("C:\\users\\Alon\\workspace\\ex2temp\\bin\\result.txt");
PrintWriter pw = new PrintWriter(fw);
chosen = getRandomInt();
pw.printf("Choice=%d", chosen);
pw.println();
while (in.hasNext())
{
cellNumber = in.nextInt();
freeSpace = in.nextInt();
if (sizeOfChosen(chosen) <= freeSpace)
{
pw.printf("%d", cellNumber);
pw.println();
break;
}
}
if (!in.hasNext())
{
pw.println("Cannot allocate memory");
pw.println();
}
pw.close();
fw.close();
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
Can anyone help please? Thanks :)
You're using the files from the ".../ext2temp/bin/.." which I assume it's Eclipse's output folder. Use the path where you have the original files.
In order to create a continuous writing on the same file, I had to append text into the existing file. I have added ", true" when creating the FileWriter. Then, I created a new BufferedWriter which received the FileWriter object, and finally, changed the PrintWriter receiving object to the bufferredWriter. This way, every time I run the program, 2 new lines of data are formed below the old ones and I get a "log file".

Try Catch logic error with file i/o in Java

So, I've been trying to learn java from various sources, I've been learning for about 2 years now. So far everything has been going smoothly, i haven't had to post on stackoverflow for a while. Recently I've been trying to figure out how to create and read files with java. I can do both of those things in separate apps, but when i try to do both it doesn't always work.
What i want to happen:
I want my program to create data.txt, then I want it to read the data and produce an error log on error.txt.
What happens:
The data.txt file gets created as expected, but nothing is written to the error.txt file. I'm having trouble grasping the try/catch block and how exactly it works. Anyone got any ideas? even just some advice would be appreciated. Thanks!
import java.io.*;
import java.util.Scanner;
public class dataReader {
public static void main(String args[]) throws Exception {
File fileName;
fileName = new File("data.txt");
PrintWriter outputFile;
outputFile = new PrintWriter(fileName);
File errorFile;
errorFile = new File("errors.txt");
PrintWriter outputErrorFile;
outputErrorFile = new PrintWriter(errorFile);
Scanner inputFile;
int recordNumber = 0;
String inputData;
outputFile.println(77);
outputFile.println("Fred");
outputFile.println(92);
outputFile.println("Wilma");
outputFile.println(89.9);
outputFile.println("Barney");
outputFile.println(42);
outputFile.println("BettyS");
inputFile = new Scanner(fileName);
while (inputFile.hasNext()) {
recordNumber++;
try {
inputData = inputFile.nextLine();
if (Integer.parseInt(inputData) < 50) {
outputErrorFile.println(recordNumber + ", " + inputData + ", is less than 50.");
} else if (Integer.parseInt(inputData) > 90) {
outputErrorFile.println(recordNumber + ", " + inputData + ", is less than 50.");
}
} catch (Exception e) {
outputErrorFile.println(recordNumber + ", That's not an integer.");
}
}
outputFile.close();
outputErrorFile.close();
System.out.println("Program terminated.");
}
}
Move the outputFile.close(); line before inputFile = new Scanner(fileName);. Currently it's just cached in the memory and not written actually to the disk.
The documentation of PrintWriter says it all. The PrintWriter(Writer) constructor creates a writer which is not automatically flushed.
You have to call close or flush method to write your data to the file.
So you have to use outputFile.close(); method before starting reading.
and as a good practice you have to close all your PrintWriter instances to avoid memory leak.
just in this case please add inputFile.close(); at the end of your program.

Index Out Of Bounds Exception when trying to read from file into ArrayList

I am trying to read a series of integers from a file into an ArrayList but when accessing numbers.get(0), I get the Out of Bounds Exception, presumably because nothing has been written to the list.
ArrayList<Integer> numbers = new ArrayList<Integer>();
public void Numbers() throws IOException{
File file = new File("Numbers.txt");
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext()){
numbers.add(inputFile.nextInt());
}
inputFile.close();
}
Any help would be greatly appreciated. I can provide more code snippets if needed.
One likely problem is that you have declared the method as
public void Numbers() throws IOException
This is a method called Numbers which returns void and throws IOException. Note that this is not a constructor, which you might intend it to be, because you have declared a return type. If you are calling numbers.get(0) in another method of this same class. This Numbers() method is probably not called explicitly if you expect it to be called automatically as a constructor.
I think its trying to read the token as int and comes out with exception. Try this:
try{
File file = new File("Numbers.txt");
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext()){
String next = inputFile.next();
try{
numbers.add(Integer.valueOf(next));
}catch(NumberFormatException nfe){
//not a number, ignore it
}
}
}catch(IOException ioe){
ioe.printStackTrace();
}

Java writeout program Unhandled exception type IOException

I'm getting multiple erros with this part of my program. What it basically does is read input from an unorganized file, PersonnelInfo.txt, and it sorts it into an array in the EmployeeInfo class (not posted because I don't believe the problem lies in that class, if you guys want, I will post it for reference).
After sorting the info (Like Name, ID number, title at the company, etc.) the program writes this to another file, ORGANIZEDPersonnelInfo.txt, which will be sorted as such:
Name: Employee name here
ID: Employee ID here
etc.
One error I am getting is in the "static FileWriter writeOut..." line and it is "Unhandled exception type IOException. I put a throws IOException in the main method declaration but it did nothing.
Next, in the "public String toString()" method I am receiving multiple errors. When I try to make it void, it says the return type is incompatible with Object.toString(). When I keep it as a String and return null it wants me to use try/catch but the main error still exists.
Please help! This is getting pretty frustrating...
import java.io.*;
import java.util.Scanner;
public class HR {
static EmployeeInfo[] employee = new EmployeeInfo[4];
static FileWriter writeOut = new FileWriter("/Users/zach/Documents/workspace/Dec. 10, 2012/src/ORAGNIZEDPersonnelInfo.txt");
static BufferedWriter out = new BufferedWriter(writeOut);
public static void main(String[] args) throws IOException {
File PersonnelInfo = new File("/Users/zach/Documents/workspace/Dec. 10, 2012/src/PersonnelInfo.txt");
Scanner inputFile = new Scanner(PersonnelInfo);
int numOfEmployees = Integer.parseInt(inputFile.nextLine());
System.out.println("Number of employees: " + numOfEmployees);
for (int i = 0; i < 4; i++) {
String name = inputFile.nextLine();
String ID = inputFile.nextLine();
String title= inputFile.nextLine();
String startDate = inputFile.nextLine();
employee[i] = new EmployeeInfo(name, ID, title, startDate);
}
listEmployeeInfo();
employee.toString();
}
public String toString() {
for (EmployeeInfo i: employee) {
out.write("Name: " + i.getName());
out.write("ID: " + i.getID());
out.write("Title: " + i.getTitle());
out.write("Start Date: " + i.getStartDate());
}
return null;
}
If you override toString() (as you're doing, since toSTring() is a method from Object, and you're redefining it in your class, which extends Object as all classes do), you should respect the contract of the overridden method, which is to return a String representation of the object (and not to write fields to a buffered writer. Name this method with another name.
Moreover, you're calling a method (out.write()) which throws a checked exception: IOException. So, either you know how to handle this exception, and you should catch it, or you don't know how to handle it, and the method should declare that it throws the exception:
public void writeToOut() throws IOException {
for (EmployeeInfo i: employee) {
out.write("Name: " + i.getName());
out.write("ID: " + i.getID());
out.write("Title: " + i.getTitle());
out.write("Start Date: " + i.getStartDate());
}
}
You have other compilation errors in your program. Each one comes with an error message, a file name and a line number. Try to understand the message, and to fix the error. Read the Java tutorial about exceptions to understand how to handle them.
If you still can't handle them after having read this tutorial, ask another question and paste the exact error message you get from the compiler.
When you are executing static void main, you are not in an instance of the class HR but rather in a static method of it. So if you want to use the toString() method you've written, you'd have to do new HR().toString()
You would be better off removing the static keyword from all the fields and creating an instance of the HR object, then opening the file in the Constructor of that object, i.e.
public HR() {
try {
this.writeOut = new FileWriter("/Users/zach/Documents/workspace/Dec. 10, 2012/src/ORAGNIZEDPersonnelInfo.txt");
} catch (IOException e) {
// handle it, etc.
}
}
public void processFile() {
// Do the stuff
}
public static void main(String[] args) {
HR myHR = new HR().processFile();
// etc.
}
This would allow you to use the toString() method and allow you to handle the exception the way you want to.
Others have addresses toString(), so I'll have a go at the FileWriter...
I'd populate writeOut in a method rather than static scope so you can catch the exception and even try a different filename or something:
FileWriter openOutputfile(String name)
{
boolean done = false;
FileWriter result = null
try {
result = new FileWriter(...);
done = true;
}
catch(IOException ex) {
// print the stack trace
// prompt for another filename
// name = read line
}
return result;
}
I would advice to move your static declaration of Writer inside your main for two reasons (one they don't need to be a static attributes and also the IOException is being handled there). Get the string from toString and use the writer to write the string in the file:
public class HR {
static EmployeeInfo[] employee = new EmployeeInfo[4];
public static void main(String[] args) throws IOException {
FileWriter writeOut =
new FileWriter("/Users/zach/Documents/workspace/"+
"Dec. 10, 2012/src/ORAGNIZEDPersonnelInfo.txt");
BufferedWriter out = new BufferedWriter(writeOut);
File PersonnelInfo = new File("/Users/zach/Documents/workspace/"+
"Dec. 10, 2012/src/PersonnelInfo.txt");
Scanner inputFile = new Scanner(PersonnelInfo);
....
//write employee string in the file
out.write(getEmployeeString());
out.close();
}
public String getEmployeeString() {
StringBuilder stringBuilder = new StringBuilder();
for (EmployeeInfo i: employee) {
stringBuilder.append("Name: " + i.getName());
stringBuilder.append("ID: " + i.getID());
stringBuilder.append("Title: " + i.getTitle());
stringBuilder.append("Start Date: " + i.getStartDate());
}
return stringBuilder.toString();
}
}
If you must need to make them as static variables then do the initialization in a static block with exception handling as below:
static FileWriter writeOut;
static BufferedWriter out;
static {
try{
writeOut =
new FileWriter("/Users/zach/Documents/workspace/"+
"Dec. 10, 2012/src/ORAGNIZEDPersonnelInfo.txt");
out = new BufferedWriter(writeOut);
}catch(IOException ioex){
ioex.printStackTrace();
}
}
Corrected toString()
public String toString() {
StringBuffer buf = new StringBuffer();
for (EmployeeInfo i: employee) {
buf.append("Name: ").append(i.getName());
buf.append("ID: ").append(i.getID());
// ....
}
return buf.toString();
}
in main you print the content:
HR hr = new HR();
out.write(hr.toString());
But I would write using an own write method "writeEmployees(out)"
see Solution of poster JB Nizet

Creating a file and writing to it

I created a file named 'test.txt' and then took input from the user to write the input to the file. Everything runs fine. The program doesn't show any error at all. The file is created and the program takes input from the user but when I checked the content of the file, it was empty. Can anyone figure out what is wrong with my code? The code is as follows.
package InputOutput;
import java.io.*;
public class CharacterFileReaderAndFileWriter{
private BufferedReader br = null;
private BufferedWriter bw = null;
private PrintWriter pw = new PrintWriter(System.out, true);
public File createFile() throws IOException{
File f = new File("test.txt");
return f;
}
public void writeToFile() throws IOException{
try{
bw = new BufferedWriter(new FileWriter(createFile()));
}
catch(FileNotFoundException ex){
ex.printStackTrace();
}
//take input from the console (user)
br = new BufferedReader(new InputStreamReader(System.in));
String s;
pw.println("Please enter something");
pw.println("To stop the program, enter 'stop'");
do{
s = br.readLine();
if(s.compareTo("stop")==0)
break;
s+= "\r\n";//adding an new line to the string s
bw.write(s);
}
while(s.compareTo("stop")!=0);
br.close();
bw.close();
}
public static void main(String[] args) throws IOException{
CharacterFileReaderAndFileWriter cfr = new CharacterFileReaderAndFileWriter();
cfr.writeToFile();
}
}
Most example programs show that you have to call.flush() on your BufferedWriter before the .close(). This should not be required, .close() should call .flush() automatically, but it doesn't hurt. Also you should call all the Stream/Writer objects .close() methods in reverse order as well, again correctly written classes should call .close() on all the object they wrap, but it doesn't hurt to do it anyway.
Other things that might catch you out later:
if(s.compareTo("stop")==0)
should be
if ("stop".equalsIgnoreCase(s))
it is more efficient, eliminates the possibility of a NullPointerException on s, handles any case of stop and most importantly more idiomatic Java than using .compareTo()
s+= "\r\n";//adding an new line to the string s
bw.write(s);
should be
bw.write(System.getProperty("line.separator"));
bw.write(s);
The s+= creates intermediate objects and garbage that needs to be collected. Hard coding line endings is bad as well.
You need close the outputstream.
file.close();

Categories