I have the basics of my program finished.
The idea is that the user can specify a shape color width height etc. Upon inputting the data, constructors are called which create output, or there are other options which create output that the user can specify.
My goal is to get all of this output into a text file.
Currently I create a scanner for reading:
static Scanner input = new Scanner(System.in);
Then in my main driver method I create a Formatter:
public static void main(String[] args) {
Formatter output = null;
try{
output = new Formatter("output.txt");
}
catch(SecurityException e1){
System.err.println("You don't have" +
" write accress to this file");
System.exit(1);
}
catch(FileNotFoundException e){
System.err.println("Error opening or" +
" creating file.");
System.exit(1);
}
After each time I expect output I have placed this bit of code:
output.format("%s", input.nextLine());
And finally I close the file with
output.close()
The file is created but it is currently blank. I know I'm on the right track, because I've tried doing this:
output.format("%d", i);
where i is an integer of 0 and the file writes correctly.
However, I cannot seem to get it to work for an entire line, or for the output at all.
Please help!
I am not an expert but why can you not just use "FileWriter"?
Is it because you want to catch those exceptions to display useful information to the user?
Or have I misunderstood the question completely? - If so, sorry and just disregard this.
import java.io.FileWriter;
import java.io.IOException;
try
{
FileWriter fout = new FileWriter("output.txt"); // ("output.txt", true) for appending
fout.write(msg); // Assuming msg is already defined
fout.close();
}
catch (IOException e)
{
e.printStackTrace();
}
Related
I'm going through a Java book and now onto Formatter class outputting into a text file. I added in an extra line of code to test for the toString() towards the end of addRecords() but it does't work. Why is it so?
Furthermore, I am a bit confused about the closeFile() at if (output != null) then close the file. From my understanding is that I thought output has already formatted all the input into the text file how about it's still not null which leads me to try out the toString() at addRecords().
Thanks in advance!
// Fig. 15.3: CreateTextFile.java
// Writing data to a sequential text file with class Formatter.
import java.io.FileNotFoundException;
import java.lang.SecurityException;
import java.util.Formatter;
import java.util.FormatterClosedException;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class CreateTextFile
{
private static Formatter output; // outputs text to a file
public static void main(String[] args)
{
openFile();
addRecords();
closeFile();
}
// open file clients.txt
public static void openFile()
{
try
{
output = new Formatter("clients.text"); // open the file
}
catch (SecurityException securityException)
{
System.err.println("Write permission denied. Terminating.");
System.exit(1); // terminate the program
}
catch (FileNotFoundException fileNotFoundException)
{
System.err.println("Error opening file. Terminating.");
System.exit(1); // terminate the program
}
}
// add records to file
public static void addRecords()
{
Scanner input = new Scanner(System.in);
System.out.printf("%s%n%s%n? ",
"Enter account number, first name, last name and balance.",
"Enter end-of-file indicator to end input.");
while (input.hasNext()) // loop until end-of-file indicator
{
try
{
// output new record to file; assumes valid input
output.format("%d %s %s %.2f%n", input.nextInt(),
input.next(), input.next(), input.nextDouble());
}
catch (FormatterClosedException formatterClosedException)
{
System.err.println("Error writing to file. Terminating.");
break;
}
catch (NoSuchElementException elementException)
{
System.err.println("Invalid input. Please try again.");
input.nextLine(); // discard input so user can try again
}
System.out.println(output.toString());
System.out.print("? ");
} // end while
} // end method addRecords
// close file
public static void closeFile()
{
if (output != null)
output.close();
}
} // end class CreateTextFile
Here's the command line output:
Enter account number, first name, last name and balance.
Enter end-of-file indicator to end input.
? 100 Bob Blue 24.98
java.io.BufferedWriter#55f96302
I added in an extra line of code to test for the toString() towards the end of addRecords() but it doesn't work. Why is it so?
It is working. But it is not doing what you apparently think it does / should do.
The javadoc for Formatter.toString() says:
"Returns the result of invoking toString() on the destination for the output."
In this case, you have created a Formatter that writes to a BufferedWriter. When Formatter.toString() calls toString() on a BufferedWriter, it doesn't give you back the stuff that you wrote to the file. Rather, it returns you what Object.toString() would return. That is described here.
If you want your Java application print out what has been written to the file, you will need to open it, read it and copy the content to System.out. And before you do that, you will need to flush() or close() the Formatter.
A simpler idea would be to look at the file using a text editor or the less command, or similar ... after the application has completed. If the file is empty or shorter than you expect, make sure that your application always closes the Formatter before terminating.
BufferedWriter uses the default toString() implementation from Object. The returned String contains the class name and the Objects hashCode().
If you want a string containing the output either use String.format or a StringWriter to format your output before you write it to the file.
Edit: as mentioned by other answers the BufferedWriter is used internally by the Formatter when it is created with a filename. Formatter.toString() calls BufferedWriter.toString() in this case.
I need to reads the number of words on http://cs.armstrong.edu/liang/data/Lincoln.txt. I wrote my program, and NetBeans isn't giving me any errors. However, the program seems to be infinite. It does not stop trying to execute, and ultimately no answer is given (or even calculated, I'm not sure). Below is the code.
import java.net.*;
import java.util.Scanner;
import java.io.IOException;
public class readDataFromWeb {
public static void main(String[] args) {
try {
URL url = new URL("http://cs.armstrong.edu/liang/data/Lincoln.txt");
int wordCount = 0;
Scanner input = new Scanner(url.openStream());
while(input.hasNext()) {
wordCount++;
}
System.out.println(url + " has " + wordCount + " words.");
}
catch (MalformedURLException ex) {
System.out.println("Invalid URL");
}
catch (IOException ex) {
System.out.println("I/O Errors: No such file");
}
}
}
I'm under the impression that at first, the variable url of type URL is declared and set to http://cs.armstrong.edu/liang/data/Lincoln.txt. Is this where I am going wrong? Have I entered something incorrectly? I can provide more information if necessary. Any stylistic or conceptual insights are also welcome; I'm trying to learn. Thanks!
You never actually read any words from the scanner. hasNext returns true because there's a word you could read... but you never actually read it, so it keeps being ready for you to read, so hasNext keeps returning true.
Just call input.next() inside the loop.
I have some code that I have been using for a long time to write to a .txt file in the csv format, but for some reason it will no longer actually produce a new file. The file writing function is executing normally and flushing and closing without any error, but then no file is created. Below is a simplified example that is still not working.
`
import java.io.FileWriter;
public class test {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String filename = "SO example";
FileWriter writer=null;
try{
writer = new FileWriter(filename);
}
catch(Exception e){
System.out.println("exception: " + e.getMessage());
}
try{
writer.append("some text\n");
System.out.println("after append");
} catch (Exception e){
System.out.println("exception: " + e.getMessage());
}
try{
writer.flush();
writer.close();
System.out.println("finished writing file "+ filename);
}catch (Exception e){
System.out.println("exception 3: "+e.getMessage());
}
}
}
`
This should create a file called "SO example, but when I search for that file on my computer, it doesn't show up. I am using Netbeans btw. Does anyone know what might be the problem?
Thanks,
Paul
I just ran your code on my computer and everything seems to work fine. I am running Ubuntu and eclipse, however.
I would recommend checking where NetBeans stores your project directory and check in there. Don't forget to refresh the directory if you are looking for the file from the directory hierarchy manager within NetBeans.
I've got a loop that reads through a text file and outputs it, now I'm trying to get it to loop through, and write what's printed out into a text file as I want it to display as HTML. This is what I've got so far for this method:
public void hChoice()
{
File fbScores = new File ("P:/SD/Assignment1/fbScores.txt");
String line = "";
try {
Scanner scanScores = new Scanner(fbScores);
while(scanScores.hasNext())
{
line = scanScores.nextLine();
stringArr = line.split(":");
if(stringArr.length == 4)
{
System.out.println("<h1>" + stringArr[0]+" [" +stringArr[2]+"] |" + stringArr[1]+" ["+ stringArr[3]+" ]<br></h1> ");
PrintWriter out = new PrintWriter("P:/SD/Assignment1/HTMLscores.txt");
out.close();
}
}
}
catch (FileNotFoundException e)
{
System.out.println("problem " +e.getMessage());
}
}
I've added the HTML tags in the print out and it prints it out fine, but I've tried several different methods to get it to print to a text file but none have worked. Pretty new to Java so any help would be much appreciated. Thankyou. :)
You've gotten your syntax and code wrong for writing to files.
Please Google and check the right syntax for writing to files using java. Plenty of resources available. You'll learn better if you try it yourself.
FYR, here is one: http://www.tutorialspoint.com/java/java_files_io.htm
I know that this type of question have been asked many times. But I didn't find any answer for myself. That's why i am asking once more.
I have got an output on my console. I want to copy the same output 1-to-1 to a file. I don't want to redirect. I want some kind of "copy" it and "write" into a file.
I hope the question is clear enough, cause I have seen that the other times, the question wasn't clear.
Anyways, I have tried it with the "System.setOut" methode. But it just redirect everything to the file.
I cannot write all the "System.out.println"s with a write() into a file, that to much.
Thanks for helping.
There is no way you can get console output. You have to do everything before printing
To Write our to a file do this.
try{
FileWriter x = new FileWriter(new File("x.txt"));
x.write("hello");
}catch(IOExecption e){
}
That will write out hello to a file
You could do something like this , the system out will happen after the log to file.
This code will append. Please This is NOT a good example of Exception handling, just an example of what you can do.
protected void writeToFileAndLog(String logEntry)
{
String file = "MyAmazingLog.txt";
try
{
FileOutputStream appendedFile = new FileOutputStream(file, true);
DataOutputStream out = new DataOutputStream(appendedFile);
out.writeBytes(String.format("%s\n", logEntry));
out.flush();
out.close();
System.out.println(logEntry);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}