Alot of people have the problem "Says File doesn't exist, but it does" but my problem is the opposite, the file doesn't exist but it says it does.
Unsure on how to solve this problem and other topics just come up with "File doesn't exist but it does", etc.
Here's my code:
package New;
import java.util.Scanner;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
public class FileEditor {
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
System.out.println("Where is the file stored ex: C:/Users/Name/Place/filename.txt");
String a = scan.nextLine();
File file = new File(a);
FileWriter writer = new FileWriter(file);
BufferedWriter bwriter = new BufferedWriter(writer);
if(!file.exists()){
System.out.println("File does not exist.");
}
else{
System.out.println("Start editing? y/n");
String b = scan.nextLine();
Don't create the FileWriter/BufferedWriter until AFTER you verify the file exists.
The file does exist. You're creating it right before you check whether it exists:
FileWriter writer = new FileWriter(file);
Related
Following is my code that I am working on for a school project. It does ok up until I try to read the animal.txt file. Can someone please tell me what I am doing wrong? I am attaching my compilation error as an image. Thanks in advance.
[input error image1
package finalproject;
//enabling java programs
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.io.FileInputStream;
import java.io.IOException;
public class Monitoring {
public static void choseAnimal() throws IOException{
FileInputStream file = null;
Scanner inputFile = null;
System.out.println("Here is your list of animals");
file = new FileInputStream("\\src\\finalproject\\animals.txt");
inputFile = new Scanner(file);
while(inputFile.hasNext())
{
String line = inputFile.nextLine();
System.out.println(line);
}
}
public static void choseHabit(){
System.out.println("Here is your list of habits");
}
public static void main(String[] args) throws IOException{
String mainOption = ""; //user import for choosing animal, habit or exit
String exitSwitch = "n"; // variable to allow exit of system
Scanner scnr = new Scanner(System.in); // setup to allow user imput
System.out.println("Welcome to the Zoo");
System.out.println("What would you like to monitor?");
System.out.println("An animal, habit or exit the system?");
mainOption = scnr.next();
System.out.println("you chose " + mainOption);
if (mainOption.equals("exit")){
exitSwitch = "y";
System.out.println(exitSwitch);
}
if (exitSwitch.equals( "n")){
System.out.println("Great, let's get started");
}
if (mainOption.equals("animal")){
choseAnimal();
}
if (mainOption.equals("habit")) {
choseHabit();
}
else {
System.out.println("Good bye");
}
}
}
\\src\\finalproject\\animals.txt suggests that the file is an embedded resource.
First, you should never reference src in you code, it won't exist once the program is built and package.
Secondly, you need to use Class#getResource or Class#getResourceAsStream in order to read.
Something more like...
//file = new FileInputStream("\\src\\finalproject\\animals.txt");
//inputFile = new Scanner(file);
try (Scanner inputFile = new Scanner(Monitoring.class.getResourceAsStream("/finalproject/animals.txt"), StandardCharsets.UTF_8.name()) {
//...
} catch (IOException exp) {
exp.printStackTrace();
}
for example
Now, this assumes that file animals.txt exists in the finalproject package
The error message clearly shows that it can't find the file. This means there's two possibilities:
File does not exist in the directory you want
Directory you want is not the directory you have.
I would start by creating a File object looking at "." (current directory) to and printing that to see what directory it looks by default. You may need to hard code the file path, depending on what netbeans is using for a default directory.
I have created a simple file read and write program. When compiling, the program shows no errors and runs without problem, but when I try to open the output file, I get a "file corrupted" error, and the size of the file is 0kb.
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
public class Extention
{
FileInputStream filein;
FileOutputStream fileout;
void asdf() throws IOException
{
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);
System.out.print("/**");
System.out.print("\n");
System.out.print("* Created by Arul on 6/15/2016 *");
System.out.print("\n");
System.out.print("**/");
System.out.print("\n");
try {
System.out.print("Enter Name of the file to read : ");
filein = new FileInputStream(br.readLine());
System.out.print("Enter Name of the file to write : ");
fileout = new FileOutputStream(br.readLine());
int i;
do {
i = filein.read();
if (i == -1)
break;
fileout.write(i);
} while (i != -1);
} catch (FileNotFoundException f) {
System.out.println("Exception : File not found!");
} finally {
filein.close();
fileout.close();
}
}
public static void main(String arg[]) throws IOException
{
Extention d = new Extention();
d.asdf();
}
}
When you say, "File corrupted", is this a Java error which you get during execution of your program, or is this an error when you double click on the created file?
If it's the latter, it all depends on what you are trying to copy. If you used it to copy an TXT file, but you changed the file ending to MP3, you would find that, when you double click on the file, your media player will be selected to open the text file and won't understand the text data.
So i am working on a code that receives 2 strings. The string are "input#.txt" or "output#.txt" the # symbol is replaced with whatever number file is used. Now in the input file is the information I need to get to. How do I determine if that input.txt file can be opened and how do I open it.
I've tried a buffered reader and trying to just make the string a file.
import java.util.*;
import java.io.*;
public class Robot {
public static void readInstructions(String inputFileName, String outputFileName) throws InvalidRobotInstructionException{
try{
BufferedReader input = new BufferedReader(new FileReader(inputFileName));
File inner = new File(inputFileName);
Scanner in = new Scanner(input);
PrintWriter wrt;
wrt = new PrintWriter(outputFileName);
if(input.readLine() == null){
System.out.println("Input file not found.");
return;
}
This will read a file in:
Scanner input = new Scanner(new File("input5.txt"));
Don't forget to add throws FileNotFoundException in your main method
edit: I see you added code.
For some reason I keep on getting the following error when I compile my code. I have the correct preprocessor directives (import statements), and no syntax errors but whenever I compile my code I am given
probably,your dateFile is empty which might be the reason for this exception
public int nextInt()
Scans the next token of the input as an int.
An invocation of this method of the form nextInt()
Returns:
the int scanned from the input
Throws:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed
refer http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#Scanner(java.io.File)
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Reader
{
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException, IOException
{
File dateFile = new File("test.txt");
FileWriter fw = new FileWriter(dateFile);
BufferedWriter bw = new BufferedWriter(fw);
Scanner reader = new Scanner(dateFile);
try
{
// if file doesnt exists, then create it
if (!dateFile.exists())
{
dateFile.createNewFile();
bw.write("1");
bw.close();
System.out.println("Done");
}else
{
int duration;
String ans = JOptionPane.showInputDialog ("Enter the amount of problems per training session (with number in minutes):");
while(!ans.matches("[0-9]+"))
{
ans = JOptionPane.showInputDialog ("Please re-enter the amount of problems per training session (with number in minutes):" );
}
duration = Integer.parseInt(ans);
System.out.println(duration);
bw.write(""+duration);
bw.flush();
int numSessions = reader.nextInt();
System.out.println("Number of sessions is: " + numSessions);
String fileName = ("sessionNumber"+numSessions);
File newSession = new File(""+fileName+".txt");
System.out.println(fileName);
if (!newSession.exists())
{
newSession.createNewFile();
System.out.println("IT DOES NOT EXIST!");
}
fw = new FileWriter(newSession.getAbsoluteFile());
bw = new BufferedWriter(fw);
bw.write(duration);
bw.close();
}
} catch (IOException e)
{
e.printStackTrace();
}
}
}
Now it should work.
I add this two lines:
bw.write(""+duration);
bw.flush();
you were never write in the File.
Remember to .flush() your buffer.. if you want it to write on the file before you close it!
notice that i changed the path of the file to let it work on my pc so change it again
I am new to java and using netbeans v8. I am trying to read strings from a file and saving modifications in a new file but when I run the code it does not show anything it continues running.
code is
package filereadingandwriting;
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
public class FileReadingAndWriting {
public static void readAndWrite() throws Exception
{
File inputFile = new File("names.txt");
Scanner input = new Scanner(System.in);
File outFile = new File("output.txt");
PrintWriter writer = new PrintWriter(outFile);
for(int i = 0;input.hasNextLine(); i++)
{
String inputLines = input.nextLine();
writer.println("Sr#" + i + " " + inputLines);
}
input.close();
} // readAndWrite function ends.
public static void main(String[] args) throws Exception {
// TODO code application logic here
readAndWrite();
} // main function ends.
} //FileReadingAnd Writing class ends.
If you want to read from your inputFile you have to change your code to:
File inputFile = new File("names.txt");
Scanner input = new Scanner(inputFile);
In your case you would read from STDIN.
Also you should use the newer java.nio.* API
Just change new Scanner(System.in); to new Scanner(inputFile);.