-
Java File IO
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);
}
}
-
I assume you have struggled w. this code
If you want to write to a plain text file, the open it, write to it and close it,
using one plain buffered writer.
Code:
import java.io.*;
import java.util.*;
public class IOTest {
final int MAX = 10;
int intValue;
String fileName = "Test.txt";
public IOTest() throws IOException {
BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
Random rand = new Random();
for (int line = 0; line <= MAX; line++) {
for (int num = 0; num <= MAX; num++) {
intValue = rand.nextInt(90) + (10);
bw.write(intValue + " ");
System.out.println(intValue + " ");
}
bw.newLine();
}
bw.close();
System.out.println("debugging, file created : " + fileName);
}
public static void main(String[] args) {
try {
new IOTest();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
eschew obfuscation
-
Solution
Solution - the Ide is Net Beans 5.0 Beta and the issue lied in
setting up the package within the project correctly.
Right click on the project name,properties,select run,
then setting the working directory to the source (scr) package
that is being used.
Reply With Quote
Similar Threads
-
Replies: 5
Last Post: 11-18-2005, 04:09 PM
-
Replies: 1
Last Post: 05-18-2005, 04:51 AM
-
By David Ayala in forum Java
Replies: 1
Last Post: 05-07-2005, 05:42 AM
-
Replies: 5
Last Post: 04-19-2001, 12:35 PM
-
By Ning Liang in forum Java
Replies: 2
Last Post: 03-23-2000, 11:42 AM
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks