Skip to main content

Java File IO

1 reply [Last post]
emoos
Offline
Joined: 2005-09-06
Points: 0

I am trying to write a list of numbers to Test.txt file which is located in the same directory as the java class file.

The program outputs the expected results to the Ide output window but when the file is checked after the program has terminated there is no data in the file - why is this?

Code :

public class IoTest {

final int MAX = 10;
int intValue;
String fileName = "Test.txt";

public IoTest () throws IOException {

Random rand = new Random();
File fileObj = new File(fileName);
FileWriter fw = new FileWriter(fileObj,true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);

for (int line = 0;line <= MAX; line++){

for (int num = 0;num <= MAX; num++){

intValue = rand.nextInt (90)+(10);
pw.print(intValue + " ");
pw.write(intValue + " ");
System.out.println(intValue + " ");
}

pw.println();
}
pw.flush ();
pw.close ();
bw.close ();
fw.close ();

System.out.println ("debugging, file created : "+ fileName);
}
}

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
destin
Offline
Joined: 2006-05-05
Points: 0

Where's your SPVM (static public void main(String[])). Try this:
[code]import java.io.*;
import java.util.*;

public class HelpFile {
final int MAX = 10;
final String fileName = "Test.txt";

static public void main(String[] args) throws IOException {
Random rand = new Random();
PrintWriter pw = new PrintWriter(new BufferedWriter(
new FileWriter(new File(fileName))));

for (int line = 0; line <= MAX; line++) {
for (int num = 0; num <= MAX; num++) {
int intValue = rand.nextInt(90) + 10;
pw.print(intValue + " ");
pw.write(intValue + " ");
System.out.println(intValue + " ");
}
pw.println();
}
pw.flush();
pw.close();
}
}
[/code]