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
Related
I'm reading a file with numbers checking if the number is a prime number then writing next to the prime numbers "is a prime" and printing that out to a different file,
I keep getting:
Failed to open file in4.txt Exiting...
This is my code:
import java.util.Scanner;
import java.util.ArrayList;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
public class CheckPrimes {
public static void checkPrimes(String in_file, String out_file) {
File temp = new File(in_file);
Scanner input;
try
{
input = new Scanner(temp);
}
catch (Exception e)
{
System.out.printf("Failed to open file %s\n", in_file);
return;
}
while (true)
{
for (int i = 2; i < input.nextInt(); i++)
{
if (input.nextInt() % i != 0)
{
try{
PrintWriter output = new PrintWriter(out_file);
output.print( input.nextInt() + " is prime");
output.close();
}
catch(IOException ex)
{
System.out.printf("Error : %s\n",ex);
}
}
}
}
{
public static void main(String[] args)
{
checkPrimes("in4.txt", "out4.txt");
System.out.printf("Exiting...\n");
}
}
Longshot but might work since someone had that problem on this site yesterday. I referred them to this answer on a different topic where the File URL is formatted differently into a path that java seems to accept better that plaintext filepaths.
For the error you are receiving (Failed to open file in4.txt), just make sure that the file you are reading is on the same file level as your JAR (or file if running in an IDE). Alternatively, you can run the createNewFile() function and edit the created function.
(IntelliJ runs the file from the base of the project, hence why my files aren't where the class file is).
However, upon running the code myself, I was receiving this error: java.util.NoSuchElementException. I was able to correct this by switching from readInt() to readLine(), and having the in4.txt file structured as shown:
1
3
5
7
9
I believe readInt() not working versus readLine() is due to the problem presented in this problem. Also, be wary of calling readLine/readInt multiple times rather than assigning a variable per loop iteration because every call progresses the scanner (more info here).
I am currently writing a program that writes class codes to a file and then reads them back from said file and prints them to the screen. Everytime I run the program I keep getting the java.util.NoSuchElementException. This problem persists after every modification I have made and I'm not sure where to go from here. Any help would be greatly appreciated.
package u2a1_readtextfilehandleexcep;
import java.io.*;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class U2A1_ReadTextFileHandleExcep {
public static void main(String[] args) throws FileNotFoundException, IOException {
//Create new file called course.txt
java.io.File file = new java.io.File("course.txt");
if (file.exists()) {
System.out.println("File already exists; try another name.");
System.exit(0);
}
//Input the specified words to the file
try (PrintWriter output = new PrintWriter(file)) {
output.println("IT2249 6 Introduction to Programming with Java");
output.println("IT2230 3 Introduction to Database Systems");
output.println("IT4789 3 Mobile Cloud Computing Application Development");
}
try (
//Reads from file to the console
Scanner input = new Scanner(file)) {
while (file.canRead()) {
String code = input.next();
int creditHours = input.nextInt();
String courseTitle = input.nextLine();
System.out.println("Course Code = " + code + " | Credit Hours = " + creditHours + " | Course Title = " + courseTitle);
}
input.close();
}
}
}
And after running the program:
Course Code = IT2249 | Credit Hours = 6 | Course Title = Introduction to Programming with Java
Exception in thread "main" java.util.NoSuchElementException
Course Code = IT2230 | Credit Hours = 3 | Course Title = Introduction to Database Systems
Course Code = IT4789 | Credit Hours = 3 | Course Title = Mobile Cloud Computing Application Development
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at u2a1_readtextfilehandleexcep.U2A1_ReadTextFileHandleExcep.main(U2A1_ReadTextFileHandleExcep.java:26)
C:\Users\Deb\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 1 second)
Once there are no more elements left to read, the Scanner will throw the exception you are seeing. Right now you continue to loop while you can read the file, but that has no bearing on where the Scanner is in the file. Scanner provides a family of functions to check the validity of the next tokens: hasNext(), hasNextInt(), hasNextLine(), etc. You should use these instead:
while( input.hasNext() ) {
String code = input.next();
// ...
}
However, if you have a malformed file, you could still get the exception for similar reasons reading the hours and titles. You can handle these by checking the scanner before reading them, or possibly in an exception handler since this probably indicates a larger problem, such as reading an unsupported or corrupt file.
Please call Scanner.hasNext(), so that the loop will terminate when
there are no more elements.
Don't close input explicitly as you are using the try-with-resources
which will take care of it.
There is no need of two separate try blocks, as they could be
combined together, once the writing is finished use the
PrintWriter.flush() to write it to disk.
package u2a1_readtextfilehandleexcep;
import java.io.*;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class U2A1_ReadTextFileHandleExcep {
public static void main(String[] args) throws FileNotFoundException, IOException {
//Create new file called course.txt
java.io.File file = new java.io.File("course.txt");
if (file.exists()) {
System.out.println("File already exists; try another name.");
System.exit(0);
}
//Input the specified words to the file
try (PrintWriter output = new PrintWriter(file);Scanner input = new Scanner(file)) {
output.println("IT2249 6 Introduction to Programming with Java");
output.println("IT2230 3 Introduction to Database Systems");
output.println("IT4789 3 Mobile Cloud Computing Application Development");
output.flush();
while (file.canRead() && input.hasNext()) {
String code = input.next();
int creditHours = input.nextInt();
String courseTitle = input.nextLine();
System.out.println("Course Code = " + code + " | Credit Hours = " + creditHours + " | Course Title = " + courseTitle);
}
}
}
}
file.canRead() will always return true and when read pointer reaches EOF, next input.read() operation fails.
Use input.hasNextLine() to check if EOF is reached.
I wrote a short script to create a file to my Desktop, and the file appeared. I just did it all in main, like so:
import java.io.*;
import java.util.Scanner;
public class FilePractice {
public static void main(String[] args) {
//create a new File object
File myFile = new File("/home/christopher/Desktop/myFile");
try{
System.out.println("Would you like to create a new file? Y or N: ");
Scanner input = new Scanner(System.in);
String choice = input.nextLine();
if(choice.equalsIgnoreCase("Y"))
{
myFile.createNewFile();
}
else
{
//do nothing
}
}catch(IOException e) {
System.out.println("Error while creating file " + e);
}
System.out.println("'myFile' " + myFile.getPath() + " created.");
}
}
I just wanted to make sure the code worked, which it did. After that, I wanted to expand by creating a file with user input, as well as define which directory the user wished to send the file to. I'm on a Linux machine, and I wanted to send it to my Desktop again, so my user input was "/home/christopher/Desktop" for the userPath. Nothing happened. I even cd'd to my Desktop via terminal to "ls" everything there, and still nothing.
Perhaps my syntax is wrong?
If this is a duplicate of anything, my apologies. I tried to do a thorough search before coming here, but I only found info on creating files and sending files to directories that are already defined as a string (e.g. File myFile = new File("/home/User/Desktop/myFileName")).
Here is the expanded attempt:
try {
System.out.println("Alright. You chose to create a new file.\nWhat would you like to name the file?");
String fileName = input.nextLine();
input.nextLine();
System.out.println("Please enter the directory where you would like to save this file.\nFor example: C:\\Users\\YourUserName\\Documents\\");
String userFilePath = input.nextLine();
File userFile = new File(userFilePath, fileName);
System.out.println("Is this the file path you wish to save to? ----> " + userFile.getPath()+"\nY or N: ");
String userChoice = input.nextLine();
if (userChoice.equalsIgnoreCase("Y")) {
userFile.createNewFile();
//print for debug
System.out.println(userFile.getPath());
}
}catch(IOException e) {
System.out.println("Error while attempting to create file " + e);
}
System.out.println("File created successfully");
My print statement for a debug attempt outputs "/home/christopher/Desktop", but not the file name appended to the directory.
Thanks for any help offered. This is just for experimentation while learning Java I/O. Since a hypothetical user may not be on the same OS as me, I can work on those methods later. I'm keeping it on my home machine, hence the Unix filepath names.
Changing input.nextLine() to input.next() solved the problem. The program was not reaching the if statement after asking the user if they were sure their entered path was the desired save point.
I also put in a simple else statement that printed out ("File not created") to verify that it was skipping it.
Anyway, question answered. :-)
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.
I've basically copied the below code from a text book. I've had this kind of error before and managed to fix it but because I'm not familiar with the Classes & Methods used I am having a bit a trouble with this one.
Below is the error thrown by the compiler.
TextReader.java:27: error: cannot find symbol output = new BufferedOutputStream(filePath.newOutputStream());
symbol: method newOutputStream()
location: variable filePath of type Path
Below is the code. It is basically supposed to get input from a user write it to a text file then read the text file and display the info to the user.
import java.nio.file.*;
import static java.nio.file.StandardOpenOption.*;
import java.io.*;
import javax.swing.JOptionPane;
public class TextReader
{
public static void main (String[]args)
{
Path filePath = Paths.get("Message.txt");
String s = JOptionPane.showInputDialog(null,"Enter text to save as a file","Text File Creator",JOptionPane.INFORMATION_MESSAGE);
byte[] data = s.getBytes();
OutputStream output = null;
InputStream input = null;
try
{
output = new BufferedOutputStream(filePath.newOutputStream());
output.write(data);
output.flush();
output.close();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Message: " + e,"Error!!",JOptionPane.WARNING_MESSAGE);
}
try
{
input = filePath.newInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String ss = null;
ss = reader.readLine();
JOptionPane.showMessageDialog(null,"Below is the information from the saved file:\n" + ss,"Reader Output",JOptionPane.INFORMATION_MESSAGE);
input.close();
}
catch (IOException ee)
{
JOptionPane.showMessageDialog(null,"Message: " + ee,"Error!!",JOptionPane.WARNING_MESSAGE);
}
}
}
Path doesn't have a method newOutputStream(). I usually use new FileOutputStream(File) for writing to files, though there might be newer API in Java 7.
You should really use an IDE, e.g. Ecplise or Netbeans, as it will instantly tell you that the method doesn't exist, and will make writing code a thousand times easier in general. For example you can press ctrl+space in Eclipse and it will bring up a list of classes/methods/variables that match the last word you typed (the list will also automatically pop up when typing a period).