I am trying to make a java program that appends text into an existing document. This is what it has gotten me at:
import java.util.*;
import java.io.*;
public class Main
{
public main(String args[])
{
System.out.print("Please enter a task: ");
Scanner taskInput = new Scanner(System.in);
String task = taskInput.next();
System.out.print(task);
PrintWriter writer = new PrintWriter("res\tasks.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();
}
}
I have some errors and do not know how to fix them. I looked at the Bufferedwriter but I don't know how it's used, and yes I have looked javadocs. C++ was not nearly this complicated. Once again, I want to know how to make the program append text to an existing file. It should be efficient enough to make into an app. Are there any good resources to teach how to write/append/read files?? javadoc is not doing it for me.
The main() method in Java has to have the following signature
public static void main(String[] args)
Without the method being declared as above, JVM would fail to run your program. And, just like you closed the PrintWriter, you need to close your Scanner too.
I suggest you get the basics of Java down before diving into File I/O because this API would throw a lot of checked Exceptions too and for someone this new to Java it would just be terribly confusing as to what the try catchs or throws are doing.
try this,
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("tasks.txt", true)));
The following should work:
public static void main(String[] args) {
try{
Formatter out = new Formatter("fileName.txt");
out.format("Write this to file");
out.close();
} catch (Exception e) {
System.out.println("An error occurred");
}
}
This is using a Formatter object to create a file (if it doesn't already exist) and then you can use the method "format" just like you would use any print method to write to the file. The try and catch is necessary for it to compile b/c the constructor of the Formatter class throws an exception that must be caught. Other than that, just make sure you type:
import java.util.Formatter;in the beginning of your file.
And btw, C++ is NOT easier than Java lol. Cheers.
Related
public static void generateOutput() {
File file = new File ("C:/Users/me/Desktop/file.txt");
PrintWriter outputFile = null;
outputFile = new PrintWriter(file);
}
Above is my code, I am trying to make a PrintWriter that writes to a file I have made on my desktop called file.txt, however I am getting the error "unhandled exception type, file not found exception". I have looked at other posts and I'm unsure why I am still getting this error. I have also tried doing so without the File object. I was hoping for some guidance as to where I went wrong
The most important idea you have to understand here, is that your file may:
not be found;
have its descriptor locked (which means, that some other process uses it);
be corrupted;
be write-protected.
In all above cases, your Java program, triggering OS Kernel, will crush, and the exception will happen at the runtime. In order to avoid this accident, Java designers decided (and well they did), that PrintWriter should throw (meaning, it is a possibility to throw) FileNotFoundException and this should be a checked exception at compile time. This way developers will avoid more serious run-time problems, like program crush crush.
Hence, you either have to:
try-catch in your method that PrintWriter; or
throw the exception one level up.
I think, your question was about why that happens. Here is the answer for both - (1) why? and (2) how to solve it.
Java has an exception catch mechanism that helps you program better. You will have to handle an exception FileNotFoundException to warn that what will happen if the program cannot find your file Or you can throws this exception. I recommend learning about exception handling in Java.
This code can help you
public static void generateOutput() {
File file = new File ("C:/Users/me/Desktop/file.txt");
PrintWriter outputFile = null;
try {
outputFile = new PrintWriter(file);
} catch (FileNotFoundException e) {
// Handle if your file not found
e.printStackTrace();
}
}
Or
public static void generateOutput() throws FileNotFoundException {
File file = new File ("C:/Users/me/Desktop/file.txt");
PrintWriter outputFile = null;
outputFile = new PrintWriter(file);
}
Assuming your file exists in the given location, you need one of the following,
public static void generateOutput() throws Exception {... Your code ...}
Or
try {
//Your code
}
catch(FileNotFoundException fnne) {
// Precise exception catching example
}
catch(Exception e) {
// Not required, but adding it to catch any other exception you might face
}
You can always use precise exception in throws/catch. You need it because, PrintWriter can has compile time exception. Basically, it means if file is not found then it can throw exception and it is known at compile time. Hence you need to use one of the approach.
In addition to that, you make 2 lines into 1 as follows,
PrintWriter output = new PrintWriter(file);
You don't need to initialize the output object to null, unless you have it on purpose.
public static void Replace_Record(String editTerm, String newItem, String newAmount, String newPrice){
String filepath="temp_Food_Item.txt";
String tempfile= "temp_Food_Item_temp.txt";
File oldFile= new File(filepath);
File newFile=new File(tempfile);
String item=""; String quantity=""; String price="";
System.out.println("working ");
try{
//System.out.println("working pt1");
FileWriter fw= new FileWriter(tempfile,true);
BufferedWriter bw= new BufferedWriter(fw);
PrintWriter pw= new PrintWriter(bw);
x = new Scanner(new File(filepath));
x.useDelimiter("[,/n]");
//System.out.println("working pt2");
while(x.hasNext()){
//System.out.println("working pt3");
item=x.next();
quantity=x.next();
price=x.next();
if(item.equalsIgnoreCase(editTerm)){
pw.println(newItem+","+newAmount+","+newPrice);
}
else{
//System.out.println("working pt4 ");
pw.println(item+","+quantity+","+price);
}
}
x.close();
pw.flush();
pw.close();
oldFile.delete();
File dump=new File(filepath);
newFile.renameTo(dump);
}
catch(Exception e){
System.out.println("Error declared");
}
}
I don't understand where I went wrong but it is printing "error declared" so I debugged and found after working pt1 it stops and goes to catch please help?
Additional info includes:
I am making a database for a restaurant and I am inputting info in txt files in the sequence item_name,item_amount,item_price so I am taking my new values from, main and passing them to the method, in theory, it first duplicates a file until it comes to the strings I wanna remove and then replaces them and goes back to copy the strings from the real files. but every time I run this I get catch.
TIA
While I can't answer your question straight away, I can offer a few ideas.
First of, catch a more explicit exception, such as IOException, FileNotFoundException. It is generally good practice to have more explicit code and it's the first step towards improved error handling.
Also do something with it, for startes you can print it in your console and use that information to debug your program. It might tell you exactly what your error is and where it is.
hello everyone thanks for helping me through this problem but I have managed to fix it I took your tips and ran multiple types of exception till I found this was a file io error and I had a problem about naming the files so the compiler could not recognize which file I was calling other than that we Gucci thank you guys
I'm trying to write a program that gets a users input that is then written to an output file called userStrings.txt. I'm also trying to stop the processing once the user inputs 'done', but I'm not sure how to accomplish this.
Here is my code:
import java.io.*;
import java.util.Scanner;
public class Murray_A04Q2 {
public static void main(String[] args) throws IOException {
// Name of the file
String fileName = "userStrings.txt";
Scanner scan = new Scanner(System.in);
try {
// FileReader reading the text files in the default encoding.
FileWriter fileWriter = new FileWriter("userStrings.txt");
// Wrapping FileReader in BufferedReader.
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("A string");
bufferedWriter.write("Another string");
bufferedWriter.write("Yet more text...");
System.out.println("Enter something, DONE to quit: ");
String input = scan.nextLine();
// Closing file
bufferedWriter.close();
}
catch (IOException ex){
System.out.println("Error writing to file " + "userStrings.txt" + "");
}
} // End of method header
} // End of class header
In order to write to a file, do I still use System.out.println? and is the bufferedWriter.write even necessary? I'm just trying to understand the I/O and writing to files better.
Thanks!
In order to write to a file, do I still use System.out.println?
No. That writes to standard output, not to your file.
If you are using println then you need to wrap your BufferedWriter with a PrintWriter. (Look at the javadocs for the System class where the out field is documented.)
and is the bufferedWriter.write even necessary?
If you are going to write directly to the BufferedWriter then yes, it is necessary, though you probably need to an appropriate "end of line" sequence. And that's where it gets a bit messy because different platforms have different native "end of line" sequences. (If you use PrintWriter, the println method picks the right one to use for the execution platform.)
I'm also trying to stop the processing once the user inputs 'done', but I'm not sure how to accomplish this.
Hint: read about the Scanner class and System.in.
Right under you take input from the console, run a while loop to test that input is not equal to "done". Inside the while loop, add input to your file and get the next line of input.
while(!input.toLowerCase().Equals("done"))
{
bufferedWriter.write(input);
input = scan.nextLine();
}
This question already has answers here:
How do I create a file and write to it?
(35 answers)
Closed 8 years ago.
I've just started on my college journey ( 'Yay' ). I'm also new to the site so feel free to lecture me on things I may have done wrong as far as asking questions is concerned.
I was given a project, which has already been graded and all, and the program should ==>> first read lines of standard input (Input file name using keyboard) and for each line of input, if the user enters exit, the application terminates; otherwise, the application interprets the line as a name of a text file. The application creates or recreates this file and writes to it two lines of output, the name of the file and the current date and time. The application then closes the file, reopens it for reading, and writes its contents to standard output. The application writes to standard output the name of the file enclosed by square brackets. After writing the file name,
the application writes the contents of the file with each line prefixed by its corresponding line
number, a full colon, and a space.
I have worded it just as my professor did, so I apologize for any unclear statements. Here's what I got for it:
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.io.File;
import java.io.ObjectInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
public class Project1
{
public static void main() throws IOException
{
String input = "";
while(!sc.equals("exit"))
{
System.out.println("Enter file here!\n Type 'exit' to terminate");
Scanner sc = new Scanner(System.in);
input = sc.nextLine();
try
{
File file = new File (input,".txt"); // Creates pointer to a file.
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
file.createNewFile();
file.getAbsolutePath();
printFileAndDate(file);
}
catch(IOException e)
{
System.out.print("Something wrong :(");
e.printStackTrace();
}
}
System.exit(0);
}
static void printFileAndDate(File temp)
{
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println("[ " + temp.getPath() + " ]");
System.out.println(dateFormat.format(cal.getTime()));
}
}
What I attempted to do there was the following:
-Get User Input => Save Input as a file => Call method "printFileAndDate" and print the file along with the current date and time in the correct format.
However, whenever I run it, it always gives me an exception error, which means the file was never really created or that it isn't able to find it.
The list of ISSUEs, I could find :
First, your main method signature is totally wrong
public static void main() throws IOException
change to
public static void main(String[] args) throws IOException
Second, it is not a good practice to throws exception inside main method.
The good practice is to use try catch block
Third, you have your Scanner varialbe after the while loop which does not make sense
while(!sc.equals("exit"))
{
System.out.println("Enter file here!\n Type 'exit' to terminate");
Scanner sc = new Scanner(System.in); <-?!!!!!!
change to
System.out.println("Enter file here!\n Type 'exit' to terminate");
Scanner sc = new Scanner(System.in);
while(!sc.equals("exit"))
{
Fourth , you define File variable this way
File file = new File (input,".txt"); <-- totally wrong
change to
File file = new File ("input.txt"); <-- if you use relative path
Fifth there is not need for System.exit(0);at the end of main method
I am new to java. I think this is the simplest problem but even i dont know how to solve this problem. I have one text file. In that file i have some words like below :
good
bad
efficiency
I want to add list of words into another by using java program. My output want to be like this
good bad
good efficiency
bad efficiency
How to get this using java program. I tried search for some ideas. But i wont get any idea. Please suggest me any ideas. Thanks in advance.
If you do not want to learn it from scratch I would recommend using the Apache Commons io library.
The FileUtils class has a simple interface to read from and write to a file.
A good place to start learning Java IO would be to look over Sun's Java Tutorials on File IO. If you're looking into how to read in individual lines, I would particularly look at Scanners. And if at some point you're looking to manipulate Strings like this without IO being heavily involved, I'd look at Java's StringBuilder.
import java.io.*;
class Test {
//--------------------------------------------------< main >--------//
public static void main (String[] args) {
Test t = new Test();
t.readMyFile();
}
//--------------------------------------------< readMyFile >--------//
void readMyFile() {
String record = null;
String rec=null;
int recCount = 0;
try {
FileReader fr = new FileReader("c:/abc/java/prash.txt");
FileReader fr1 = new FileReader("c:/abc/java/pras.txt");
BufferedReader br = new BufferedReader(fr);
BufferedReader br1 = new BufferedReader(fr1);
record = new String();
rec = new String();
while ((record = br.readLine()) != null && (rec=br1.readLine())!=null) {
// recCount++;
System.out.print(record +" "+ rec);
//System.out.print(rec);
}
} catch (IOException e) {
// catch possible io errors from readLine()
System.out.println("Uh oh, got an IOException error!");
e.printStackTrace();
}
} // end of readMyFile()
} // end of class