static boolean exists(String location) {
File path = new File(location);
if (path.exists()){
return true;
}
else {
return false;
}
}
static boolean checkFile(String location1) throws IOException {
if ( exists(location1) ) {
File file = new File(location1);
RandomAccessFile raf = new RandomAccessFile(file, "r");
raf.seek( raf.length()-1 );
byte lastByte = raf.readByte();
raf.close();
if (lastByte == 2) {
return true;
}
else {
return false;
}
}
else {
System.out.println("File does not exist, please try again: ");
Scanner sk = new Scanner(System.in);
String newLocation = sk.nextLine();
checkFile(newLocation);
sk.close();
return false;
With that said, I have checked with a separate method whether a file even exists, however, I would like to now compress the above into a single method by somehow recursively utilizing the try-catch:
static boolean checkFile(String location) {
try {
File file = new File(location);
}
catch (FileNotFoundException e) {
System.out.println("File does not exist, please try again: ");
Scanner sk = new Scanner(System.in);
String newLocation = sk.nextLine();
checkFile(newLocation);
}
//the following if-sentence checking whether some byte checks up.
}
1st problem: how can I create a new random access file using the File file inside try? I did try initializing it before try File file = null; , but then it throws NullPointer, because after it catches the exception, the method is called again and the file will automatically be null.
Another idea was to try-catch inside a do-while-loop , but then I was thinking about do while what? I would have to check whether the file exists, considering that's what I'm already doing with try-catch it becomes redundant.
What can I do to try-catch as long as I input a path that is not a file and then proceed with the if sentence all in one method?
If you have to use try/catch, which I really don't recommend, you could do it in a "forever" loop, something like this.
public static FileReader readerForPromptedFile() {
Scanner keyboard = new Scanner(System.in);
while (true) {
try {
System.out.println("Please enter a file name");
String fileName = keyboard.nextLine();
return new FileReader(fileName);
} catch (FileNotFoundException e) {
System.out.println("File not found, please try again");
}
}
}
Something like this should work:
static boolean checkFile(String location) {
while (!exists(location)){
System.out.println("File does not exist, please try again: ");
Scanner sk = new Scanner(System.in);
String newLocation = sk.nextLine();
}
try {
//the following if-sentence checking whether some byte checks up.
}
catch (IOException e) {
// Handle exception
}
}
It's generally frowned on to use a method which could throw an exception if there is a reasonable way to check whether it should work first - in that case the behaviour isn't really an exception, it's more of a precondition. It also adds quite a large performance overhead.
Related
I am having to make a gui project for my CSIS class and I am having trouble with the read and Write I am using. I am making a game where you battle stuff and after you beat five of them it shows a message saying "YOU WIN". Every time you win a battle, I have it write the number of wins to a file so if you were to close the game you can continue when it is opened again. Here is the code that i have Written - this is my read method.
private static int read()
{
int returnValue = 0;
try(Scanner reader = new Scanner("wins.txt"))
{
while(reader.hasNextLine())
{
String read = reader.nextLine();
returnValue = Integer.parseInt(read);
}
}
catch(NullPointerException e)
{
System.out.println("No such File! Please Try Again! " + e.getMessage());
}
return returnValue;
and this is my Write method.
private static void write(int wins)
{
try(Formatter writer = new Formatter("wins.txt");)
{
writer.format("%d", wins);
}
catch (FileNotFoundException e)
{
System.out.println("File not Found!!");
}
}
the only thing that is in the wins.txt file is the number that the Write method writes into it. so i win once then the file will have "1" and if i win twice then it will have "2"
Whenever I run the program, it throws a NumberFormatException. I am not sure why it is doing this because I am parseing the String that that reader reads into an int.
The problem is that this code...
Scanner reader = new Scanner("wins.txt")
... constructs a Scanner with the literal text "wins.txt", not the contents of the file "wins.txt".
To read a file with a Scanner, the easiest way for you is probably to construct it using a File object...
Scanner reader = new Scanner(new File("wins.txt"))
There are some other changes you will need to make to your code to get it to work from this point, but this should cover the major issue.
So this may or may not be a dumb question but here we go!
So I'm trying to write to a file and it doesn't override but it writes over and over again so I need help.
Method:
#SuppressWarnings("resource")
public static void writeFile(File file, String index) {
try {
boolean wri = false;
PrintWriter out = new PrintWriter(new FileWriter(file, true));
Scanner scanner = new Scanner(file);
while(scanner.hasNext()) {
String str = scanner.nextLine();
if(str.equals(index)) {
System.out.println(index);
scanner.close();
wri = true;
break;
} else {
wri = false;
break;
}
}
if(wri != false)
return;
out.write(index);
out.write("\n");
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
You code is full of errors.
Don't use hasNext() with nextLine(). Use hasNextLine() instead.
You don't close scanner if index is not found.
You don't close out if index is found.
You open file for writing, even if you don't need to write anything.
You ignore exceptions.
if(wri != false) is a very obscure way to write if (wri).
No need to wrap FileWriter in a PrintWriter if you're only using write() method.
Since you explicitly call FileWriter constructor in append mode, I'd assume you want to write index to file, if and only if file doesn't already contain that text.
Please be aware that your logic will not work if index contains line break characters.
Since you're only reading lines, you should use BufferedReader instead of Scanner, since Scanner has a very large overhead.
As for your lack of closing the resources, use try-with-resources.
Your code should be like this:
public static void writeFile(File file, String index) {
if (file.exists()) {
try (BufferedReader in = new BufferedReader(new FileReader(file))) {
for (String line; (line = in.readLine()) != null; )
if (line.equals(index))
return;
} catch (Exception e) {
throw new RuntimeException("Error reading file: " + file, e);
}
}
try (FileWriter out = new FileWriter(file, true)) {
out.write(index);
out.write(System.lineSeparator());
} catch (Exception e) {
throw new RuntimeException("Error appending to file: " + file, e);
}
}
Test
File file = new File("C:/temp/test.txt");
writeFile(file, "Hello");
writeFile(file, "World");
writeFile(file, "Hello");
File Content
Hello
World
try with false
PrintWriter out = new PrintWriter(new FileWriter(file, false));
Please bear with me here as I'm new to the site.
below is a program that I've written for my programming in Java class, and while most of it has gone well so far, I can't seem to get rid of a specific bug.
When the program reaches the third if block (choice == 3) it doesn't let the user enter any data, and if the line
"outputStream = openOutputTextFile(newerFileName);"
is present in the if block then a FileNotFoundException occurs. After tinkering around with my code for a while I've found that the error is being thrown because the program cannot find the inputStream anymore. Although I've checked and have found that the program can still find, read, and write to the file that is throwing the error.
I'm thinking that since the error only occurs when I put the outputStream in, and is being thrown by the inputStream, then it probably has something to do with file streams. I just don't know what exactly
Does anyone have any ideas on how I could solve this issue?
public class FileProgram {
public static PrintWriter openOutputTextFile(String fileName)
throws FileNotFoundException {
PrintWriter toFile = new PrintWriter(fileName);
return toFile;
}
public static Scanner readFile(String fileName)
throws FileNotFoundException {
Scanner inputStream = new Scanner(new File(fileName));
return inputStream;
}
public static void main(String args[]) throws FileNotFoundException {
ArrayList<String>fileReader = new ArrayList<String>(10);
PrintWriter outputStream = null;
Scanner inputStream = null;
Scanner keyboard = new Scanner(System.in);
try {
System.out.println("Enter the name of the text file you want to copy.");
String oldFileName = keyboard.nextLine();
inputStream = readFile(oldFileName);
while(inputStream.hasNextLine()) {
String currentLine = inputStream.nextLine();
fileReader.add(currentLine);
}
System.out.println("All data has been collected. Enter the name for the new text file");
String newFileName = keyboard.nextLine();
outputStream = openOutputTextFile(newFileName);
File userFile = new File(newFileName);
if(userFile.exists())
{
System.out.println("The name you entered matches a file that already exists.");
System.out.println("Here are your options to fix this issue.");
System.out.println("Option 1: Shut down the program.");
System.out.println("Option 2: Overwrite the old file with the new empty one.");
System.out.println("Option 3: Enter a different name for the new file.");
System.out.println("Enter the number for the option that you want.");
int choice = keyboard.nextInt();
if(choice == 1) {
System.exit(0);
} else if(choice == 2) {
outputStream = new PrintWriter(newFileName);
} **else if(choice == 3) {
System.out.println("Enter a different name.");
String newerFileName = keyboard.nextLine();
outputStream = openOutputTextFile(newerFileName);
}**
}
for(int i = 0; i < fileReader.size(); i++) {
String currentLine = fileReader.get(i);
outputStream.println(currentLine);
//System.out.println(currentLine);
}
System.out.println("The old file has been copied line-by-line to the new file.");
}
catch(FileNotFoundException e) {
System.out.println("File not found");
System.out.println("Shutting program down.");
System.exit(0);
}
finally {
outputStream.close();
inputStream.close();
}
}
}
You are having trouble getting a line of input from your Scanner object after calling .nextInt(). In response to the numeric choice, the user enters an integer followed by a newline.
This line reads the integer from the input buffer:
int choice = keyboard.nextInt();
However, there's still a newline in the input buffer right after the number. Thus when you call .nextLine():
String oldFileName = keyboard.nextLine();
You get an empty line. You cannot create a file with an empty string for a file name, so a FileNotFoundException is thrown (this is per spec, see the other answer).
One solution is to consistently use .nextLine(), getting a line at a time from the input buffer. When you need an integer, simply parse the string manually:
int choice = Integer.parseInt( keyboard.nextLine() );
By the way, in debugging this sort of issue it's very useful to get into the habit of adding some printout statements to see what's going on:
public static PrintWriter openOutputTextFile(String fileName)
throws FileNotFoundException {
System.out.println( "Trying to create file: '" + fileName + "'" );
PrintWriter toFile = new PrintWriter(fileName);
return toFile;
}
There are more advanced debugging techniques, but this one is extremely simple, and using it is a lot more effective than using nothing at all.
I have to read a text and I created a method
public void load(String fname){
try{
BufferedReader reader = new BufferedReader(new FileReader(fname));
String id_cliente = reader.readLine();
while(id_cliente!=null){
String name_surname = reader.readLine();
int num_titoli = Integer.parseInt(reader.readLine());
String[] sb = name_surname.split(" ");
Cliente cl = new Cliente(id_cliente,sb[0],sb[1]);
clientilist.put(Integer.parseInt(id_cliente.substring(1)),cl);
for(int i = 0; i < num_titoli; i++){
cl.addTitolo(String titolo = reader.readLine());
}
id_cliente = reader.readLine();
}
}
catch(FileNotFoundException fnfe){
try{
}
catch(FileNotFoundExeption fnfe){
System.exit(0);
}
}
catch(IOException ioe){
}
}
what I would do is to check if the fname file exists.if it's not a FileNotFoundExceptionwill be thrown.Inside it I have to try to open another file.if it is not present so exit with an error message.how can i do?
In the catch block of the first try catch statement you could put any code you want and it will be executed when the exception occurs. You could read another file, try reading the same file again, ask user to point to the correct file, ...
But as mentioned a better solution is to check if the file exists before you create the reader. And if that fails you can fallback on another file (what if that one fails also?)
In the next code I adapted your method to have a check and throw an exception if file isn't valid. On using that method you can react on that. Note that you haven't opened any readers if you gave 2 invalid filenames.
try{
load(fname);
}catch(Exception e){
try{
load(alternativeFName);
}catch(Exception e){
System.out.println("None of the files are available");
e.printStackTrace();
}
}
And this is how your load function would look like:
public void load(String fname) throws Exception {
// try opening file
File file = new File(fname);
// check if valid file
if( !file.exists() ){
// if no valid file throw exception so we can react on that
throw new Exception("File not available: "+fname);
}
//your code for reading here, at this point you know the file exists
//...
}
It´d be simpler to check first if the file exist, instead of waiting for the exception:
File f = new File(fname);
if (!f.exists()) {
// similarly, check for the existence of the other file, exit if necessary
}
I'm sure there is a fairly simple answer to this question, so here we go.
I'm trying to use a FileWriter to write text to a file. My program reads text in from an already existing file, specified by the user and then asks whether to print the text to the console or to a new file, also to be named by the user.
I believe my problem is with passing the FileWriter to the "FileOrConsole" method. Am I not passing or declaring the FileWriter in the "FileOrConsole" method correctly? The file is always created but nothing is written to it.
Here is the code:
import java.io.*;
import java.util.*;
public class Reader {
public static void main(String[] args) throws IOException {
Scanner s = null, input = new Scanner(System.in);
BufferedWriter out = null;
try {
System.out.println("Would you like to read from a file?");
String answer = input.nextLine();
while (answer.startsWith("y")) {
System.out.println("What file would you like to read from?");
String file = input.nextLine();
s = new Scanner(new BufferedReader(new FileReader(file)));
System.out
.println("Would you like to print file output to console or file?");
FileOrConsole(input.nextLine(), s, input, out);
System.out
.println("\nWould you like to read from the file again?");
answer = input.nextLine();
}
if (!answer.equalsIgnoreCase("yes")) {
System.out.println("Goodbye!");
}
} catch (IOException e) {
System.out.println("ERROR! File not found!");
// e.printStackTrace();
} finally {
if (s != null) {
s.close();
}
if (out != null) {
out.close();
}
}
}
public static void FileOrConsole(String response, Scanner s, Scanner input,
BufferedWriter out) {
if (response.equalsIgnoreCase("console")) {
while (s.hasNext()) {
System.out.println(s.nextLine());
}
} else if (response.equalsIgnoreCase("file")) {
System.out.println("Name of output file?");
response = input.nextLine();
try {
out = new BufferedWriter(new FileWriter(response));
} catch (IOException e) {
e.printStackTrace();
}
while (s.hasNext()) {
try {
out.write(s.nextLine());
out.newLine();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("Sorry, invalid response. File or console?");
response = input.nextLine();
FileOrConsole(response, s, input, out);
}
}
}
you make classic error forgetting that parameters passed by value in case of java it is a value of the reference. The thing is that your assignment
out = new BufferedWriter(new FileWriter(response));
actually does not change the variable declared in main() it stays null
BufferedWriter out = null;
and then in finally it skips the close() by the if(out==null)
and as it is Buffered and you do no flush nothing is written to file.
what you got to do is out.close(); in side the FileOrConsole method call
OR
do the out = new BufferedWriter(new FileWriter(response));
outside of it. You choose :-)
Try flushing your stream, but more importantly, remember to close it.
Here's a code example of recommended practice for handling streams. Same approach can be used for input streams too and things like database code where it's important to always clean up after yourself to get the expected results.
BufferedWriter out = null;
try {
out = // ... create your writer
// ... use your writer
} catch(IOException ex) {
// maybe there was a problem creating or using the writer
} finally {
if (null != out) {
out.flush();
out.close();
out = null;
}
}