How to check if a file exists in java - java

Im having a problem in checking if a file exists in Java. However the IF block seems to work , but the ELSE seems dont. see, when a file exist, it will prompt a box that says, 'File found.' which happens in my program whenever a file do exist, the problem is errors flood in my console when a file dont exist. Can somebody tell me what's the easier and shorter way of coding my problem? thanks ! here's my code
public void actionPerformed(ActionEvent e) {
BufferedReader br = null;
File f = new File(textField.getText());
String path = new String("C:\\Users\\theBeard\\workspace\\LeapYear\\");
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(path+f));
if (f.exists())
{
JOptionPane.showMessageDialog(null, textField.getText()+" found" );
while ((sCurrentLine = br.readLine()) != null) {
textArea.append(sCurrentLine);
textArea.append(System.lineSeparator());
}
}
else
{
JOptionPane.showMessageDialog(null, textField.getText()+" not found" );
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (br != null)
{
br.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
});

The problem is with this line:
br = new BufferedReader(new FileReader(path+f));
You're appending a File to a String, which doesn't make sense. You should append a String to a String, in this case textField.getText()) appended to path.
This line will throw an exception if the file doesn't exist as per the documentation of FileReader:
Throws:
FileNotFoundException - if the named file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.
This causes your program to reach the catch clause and print an exception stack trace. You should only call this line when f.exists() returns true:
if (f.exists())
{
br = new BufferedReader(new FileReader(path + textField.getText()));
...
}

Look at these lines of your code:
br = new BufferedReader(new FileReader(path+f));
if (f.exists())
You are trying to open the file before checking whether it exists. So if the attempt to open it fails with a FileNotFoundException, the test is never reached.

String path = "C:\\Path\\To\File\\Directory\\";
String fileName = "NameOfFile.ext";
File f = new File(path, fileName);
if(f.exists()) {
//<code for file existing>
} else {
//<code for file not existing>
}

You have to instantiate the BufferedReader after checking the existence of the file.
String path = new String("C:\\Users\\theBeard\\workspace\\LeapYear\\");
File f = new File(path + textField.getText());
...
if (f.exists())
{
br = new BufferedReader(new FileReader(f.getAbsolutePath())); // or br = new BufferedReader(f);
...

Related

Why can't I neither delete nor rename the file?

While creating a method to my class, I got an unexpected problem. I've tried solutions from other theards, but they just don't work for me. My method should simply find the line specified, copy the file skipping unnecessary line, delete the original file and rename temporary file to the name of original file. It succesfuly creates new file as expected, but then fails to delete previous one as it fails to rename temporary file to original. I can't figure out, why?
void lineDelete(String file_name, String line_to_erase){
try {
int line_number = 0;
String newline = System.getProperty("line.separator");
File temp = new File("temporary.txt");
File theFile = new File(file_name+".txt");
String path = theFile.getCanonicalPath();
File filePath = new File(path);
BufferedReader reader = new BufferedReader(new FileReader(file_name + ".txt"));
BufferedWriter writer = new BufferedWriter(new FileWriter(temp));
String lineToRemove = line_to_erase;
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)){
continue;
}
writer.write(currentLine + newline));
}
writer.close();
reader.close();
filePath.delete();
temp.renameTo(theFile);
}
catch (FileNotFoundException e){
System.out.println(e);
}
catch (IOException e){
System.out.println(e);
}
Try this code:
void lineDelete(String file_name, String line_to_erase){
try {
int line_number = 0;
String newline = System.getProperty("line.separator");
File temp = new File("temporary.txt");
File theFile = new File(file_name+".txt");
String path = theFile.getCanonicalPath();
BufferedReader reader = new BufferedReader(new FileReader(theFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(temp));
String lineToRemove = line_to_erase;
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)){
continue;
}
writer.write(currentLine + newline));
}
writer.close();
reader.close();
theFile.delete();
temp.renameTo(file_name + ".txt");
}
catch (FileNotFoundException e){
System.out.println(e);
}
catch (IOException e){
System.out.println(e);
}
I could suggest a couple of reasons why the delete and/or rename might fail, but there is a better way to solve your problem than guessing1.
If you use Path and the Files.delete(Path) and Files.move(Path, Path, CopyOption...) methods, they will throw exceptions if the operations fail. The exception name and message should give you clues as to what is actually going wrong.
The javadoc is here and here.
1 - Here are a couple of guesses: 1) the file has been opened elsewhere, and it is locked as a result. 2) You don't have access to delete the file.

Using a Dynamic path for a csv file

I have a program that saves on a file. The current code is set for the file to save on a specific path, but when I run the program from a different computer the program doesn't work and I need to change the path everytime.
public CreateCustomer() {
initComponents();
ArrayList<String> ConsIDList = new ArrayList<String>();
String csvFileToRead = "E:\\ryan_assignment_sit2\\ConsID\\consID.csv"; // Reads the CSV File.
BufferedReader br = null; // Creates a buffer reader.
String line = "";
String splitBy = ","; // Reader Delimiter
try {
br = new BufferedReader(new FileReader(csvFileToRead)); // Buffer Reader with file name to read.
Scanner reader = new Scanner(System.in);
while ((line = br.readLine()) != null) { //While there is a line to read.
reader = new Scanner(line);
reader.useDelimiter(splitBy);
while (reader.hasNext()) { // While there is a next value (token).
ConsIDList.add(reader.next());
}
}
} catch (FileNotFoundException exception) { // Exception Handler if the File is not Found.
exception.printStackTrace();
} catch (IOException exception) { // Input/Output exception
exception.printStackTrace();
} finally {
if (br != null) {
try {
br.close(); // Close the Scanner.
} catch (IOException exception) {
exception.printStackTrace();
}
}
I placed the file in the a subfolder in the program with the name ConsID and I tried changing the path file to
String csvFileToRead = "..\\ConsID\\consID.csv";
But the file can't be read from the program.
String csvFileToRead = "E:\ryan_assignment_sit2\ConsID\consID.csv";
The above path will only be applicable to windows. If you execute the program in linux environment you will get an Filenotfoundexception. Eventhough you change the file, again you are hardcoding the file path.
Better you can get it as runtime parameters so that the program will be executed irrespective of OS.
If you are running you program from command line then you can place the csv file in your classpath (root folder where the class files are generated) and refer to it as below:
BufferedReader br = new BufferedReader(ClassLoader.getResourceAsStream("consID.csv"));

How to copy a text file, and print out the original and copied file in Java

I'm doing a program that needs to take a text file (test.txt) and make a copy of it and print it out. So far I am only able to print out the original file. I have searched for a way of doing this but there doesn't seem to be any help that I can understand, I am very new to java. I am at least looking for guidance, not just the full answer.
my code so far...
import java.io.*;
public class Copy{
public static void main(String [] args){
try{
FileInputStream fis = new FileInputStream("test.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
File a = new File("test.txt");
FileReader fr = new FileReader(a);
File b = new File("Copied.txt");
FileWriter fw = new FileWriter(b);
while(true){
String line = br.readLine();
if(line != null){
System.out.println(line);
} else{
br.close();
break;
}
}
} catch(FileNotFoundException e){
System.out.println("Error: " + e.getMessage());
} catch(IOException e){
System.out.println("Error: " + e.getMessage());
}
}
}
Again any bit of help will be greatly appreciated since I am trying to learn this. Thank you
Normally, I'd recommend using Files.copy just for it's simplicty, but since you need to "print" the content at the same time, we can make use of your code.
First, however, as a general rule of thumb, if you open it, you should close it. This makes sure that you're not leaving resources open which might affect other parts of your code.
See The try-with-resources Statement for more details.
Next, once you've read a line of text from the source file, you actually need to write it to the destination file, for example...
try (BufferedReader br = new BufferedReader(new FileReader("test.txt"))) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("Copied.txt"))) {
String text = null;
while ((text = br.readLine()) != null) {
System.out.println(text);
bw.write(text);
bw.newLine();
}
}
} catch (FileNotFoundException e) {
System.out.println("Error: " + e.getMessage());
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
You can use Files.copy() if you are using Java 1.7 or higher
File src = "your File";
File dest = "your copy target"
Files.copy(src.toPath(),dest.toPath());
Link to Javadoc
Change your FileWriter into a PrintStream:
PrintStream fw = new PrintStream(b);
Then you should be able to write to that file using:
fw.println(line);

Unable to open file in JAVA

I am trying to open a file in JAVA using BufferedReader but it cannot open the file. Here is my code
public static void main(String[] args) {
try
{
BufferedReader reader = new BufferedReader(new FileReader("test.txt"));
String line = null;
while ((reader.readLine()!= null))
{
line = reader.readLine();
System.out.println(line);
}
reader.close();
}
catch(Exception ex)
{
System.out.println("Unable to open file ");
}
}
It goes to the exception and prints Unable to open file. Any suggestions why I cannot able to read it.
If you want to be more nearly modern, try the Java 7 solution, taken from the Paths Javadoc:
final Path path = FileSystems.getDefault().getPath("test.txt"); // working directory
try (final Reader r = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
String line = null;
while ((line = r.readLine()) != null) {
System.out.println(line);
}
} // No need for catch; let IOExceptions bubble up.
// No need for finally; try-with-resources auto-closes.
You'll need to declare main as throwing IOException, but that's okay. You have no coherent way of handling IOException anyway. Just read the stack trace if an exception is triggered.
I don't know why this happened, but the problem seemed that I did not enter the complete path for the file even though the file was in the same folder. Ideally if the file is in the same folder then I wouldn't need to enter the entire pathname.
Try doing a check if it exists first:
File file = new File("test.txt");
if (!file.exists()) {
System.err.println(file.getName() + " not found. Full path: " + file.getAbsolutePath());
/* Handling code, or */
return;
}
BufferedReader reader = new BufferedReader(new FileReader(file));
/* other code... */

Reading multiple text file in Java

I have few text files. Each text file contains some path and/or the reference of some other file.
File1
#file#>D:/FilePath/File2.txt
Mod1>/home/admin1/mod1
Mod2>/home/admin1/mod2
File2
Mod3>/home/admin1/mod3
Mod4>/home/admin1/mod4
All I want is, copy all the paths Mod1, Mod2, Mod3, Mod4 in another text file by supplying only File1.txt as input to my java program.
What I have done till now?
public void readTextFile(String fileName){
try {
br = new BufferedReader(new FileReader(new File(fileName)));
String line = br.readLine();
while(line!=null){
if(line.startsWith("#file#>")){
String string[] = line.split(">");
readTextFile(string[1]);
}
else if(line.contains(">")){
String string[] = line.split(">");
svnLinks.put(string[0], string[1]);
}
line=br.readLine();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Currently my code reads the contents of File2.txt only, control does not come back to File1.txt.
Please ask if more inputs are required.
First of all you are jumping to another file without closing the current reader and when you come back you lose the cursor. Read one file first and then write all its contents that match to another file. Close the current reader (Don't close the writer) and then open the next file to read and so on.
Seems pretty simple. You need to write your file once your svnLinks Map is populated, assuming your present code works (haven't seen anything too weird in it).
So, once the Map is populated, you could use something along the lines of:
File newFile = new File("myPath/myNewFile.txt");
// TODO check file can be written
// TODO check file exists or create
FileOutputStream fos = null;
OutputStreamWriter osw = null;
BufferedWriter bw = null;
try {
fos = new FileOutputStream(newFile);
osw = new OutputStreamWriter(fos);
bw = new BufferedWriter(osw);
for (String key: svnLinks.keySet()) {
bw.write(key.concat(" my separator ").concat(svnLinks.get(key)).concat("myNewLine"));
}
}
catch (Throwable t) {
// TODO handle more gracefully
t.printStackTrace();
if (bw != null) {
try {
bw.close();
}
catch (Throwable t) {
t.printStackTrace();
}
}
Here is an non-recursive implementation of your method :
public static void readTextFile(String fileName) throws IOException {
LinkedList<String> list = new LinkedList<String>();
list.add(fileName);
while (!list.isEmpty()) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(new File(list.pop())));
String line;
while ((line = br.readLine()) != null) {
if (line.startsWith("#file#>")) {
String string[] = line.split(">");
list.add(string[1]);
} else if (line.contains(">")) {
String string[] = line.split(">");
svnLinks.put(string[0], string[1]);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
br.close();
}
}
}
Just used a LinkedList to maintain the order. I suggest you to add some counter if you to limit the reading of files to a certain number(depth). eg:
while (!list.isEmpty() && readCount < 10 )
This will eliminate the chance of running the code to infinity(in case of circular reference).

Categories