Skip to content
Fix Code Error

How do I check if a file exists in Java?

March 13, 2021 by Code Error
Posted By: Anonymous

How can I check whether a file exists, before opening it for reading in Java (the equivalent of Perl’s -e $filename)?

The only similar question on SO deals with writing the file and was thus answered using FileWriter which is obviously not applicable here.

If possible I’d prefer a real API call returning true/false as opposed to some “Call API to open a file and catch when it throws an exception which you check for ‘no file’ in the text”, but I can live with the latter.

Solution

Using java.io.File:

File f = new File(filePathString);
if(f.exists() && !f.isDirectory()) { 
    // do something
}
Answered By: Anonymous

Related Articles

  • Reference - What does this regex mean?
  • How is Perl's @INC constructed? (aka What are all…
  • How can I resolve Web Component Testing error?
  • GLYPHICONS - bootstrap icon font hex value
  • easiest way to extract Oracle form xml format data
  • How can I update specific parts of a text file in java?
  • Issue with iron-ajax request
  • How do the PHP equality (== double equals) and…
  • Examples of GoF Design Patterns in Java's core libraries
  • javascript .replace and .trim not working in vuejs
  • java IO Exception: Stream Closed
  • How do you round a floating point number in Perl?
  • Fastest way to write huge data in text file Java
  • How to append text to an existing file in Java?
  • Install pip in docker
  • How do I get the full path to a Perl script that is…
  • When I'm testing a web app by JUnit and Mockito I…
  • Unable to run Robolectric and Espresso with a…
  • TLS 1.3 server socket with Java 11 and self-signed…
  • The APR based Apache Tomcat Native library was not…
  • What is Common Gateway Interface (CGI)?
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • Vue set up IntersectionObserver
  • Quickly getting to YYYY-mm-dd HH:MM:SS in Perl
  • jQuery Mobile: document ready vs. page events
  • How do i arrange images inside a div?
  • Jetpack Compose and Hilt Conflict
  • Overwriting txt file in java
  • Create whole path automatically when writing to a new file
  • TypeError: Cannot read property 'webpackJsonp' of undefined
  • How does PHP 'foreach' actually work?
  • Smart way to truncate long strings
  • What is your most productive shortcut with Vim?
  • Check synchronously if file/directory exists in Node.js
  • SecurityException: Permission denied (missing…
  • How do I enter a multi-line comment in Perl?
  • Arduino error: does not name a type?
  • Set the filename for file download with use of Fetch()
  • Create a directory if it does not exist and then…
  • How to fix a locale setting warning from Perl
  • JUNIT @ParameterizedTest , Parameter resolution Exception
  • Gradle error: Execution failed for task…
  • Neither BindingResult nor plain target object for…
  • Eclipse will not start and I haven't changed anything
  • ClassNotFoundException:…
  • Best approach to real time http streaming to HTML5…
  • What are the undocumented features and limitations…
  • PHP recursive function not allowing page to load
  • ExpressJS How to structure an application?
  • data.table vs dplyr: can one do something well the…
  • create pascol voc xml from csv
  • Using PHP to upload file and add the path to MySQL database
  • Callback functions in C++
  • RegEx match open tags except XHTML self-contained tags
  • Named regular expression group "(?Pregexp)": what…
  • How do I get the name of the currently-running Perl script?
  • What's the difference between Perl's backticks,…
  • Java fileReader not reading files properly
  • org.hibernate.QueryException: could not resolve…
  • How to use java.net.URLConnection to fire and handle…
  • How to download and save an image in Android
  • Execution failed for task…
  • org.gradle.api.tasks.TaskExecutionException:…
  • SQLException: No suitable Driver Found for…
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • Check if a path represents a file or a folder
  • phantomjs: document.querySelectorAll() not working…
  • android studio 0.4.2: Gradle project sync failed error
  • Flashing a GUI button using Perl & Ttk on a Mac
  • Unhandled Promise Rejection when trying to call…
  • How do I iterate through the files in a directory in Java?
  • How can I find the product GUID of an installed MSI setup?
  • Can't access Eclipse marketplace
  • Returning a boolean from a Bash function
  • How to parse an RSS feed using JavaScript?
  • Working with strings in C, strcat and the strange…
  • Sort table rows In Bootstrap
  • Requested bean is currently in creation: Is there an…
  • Android- Error:Execution failed for task…
  • How can I check if a file exists in Perl?
  • How to add a new line of text to an existing file in Java?
  • How to properly do JSON API GET requests and assign…
  • LNK2019 símbolo externo public: bool __thiscall ……
  • Docker compose fails to start a service with an…
  • JOptionPane YES/No Options Confirm Dialog Box Issue
  • Android Webview - Completely Clear the Cache
  • How to resolve…
  • Upload video files via PHP and save them in…
  • Java - Writing strings to a CSV file
  • TypeScript metadata reflection references other…
  • How to convert java.util.Date to java.sql.Date?
  • How to execute XPath one-liners from shell?
  • What's the easiest way to install a missing Perl module?
  • update file based on a key in C
  • How to scrape all the pages in the website
  • How to fix 'Notice: Undefined index:' in PHP form action
  • Convert array to nested JSON object - Angular Material tree
  • How do I install Java on Mac OSX allowing version switching?
  • What's the difference between eval, exec, and compile?
  • Matching identical columns

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

JavaScript sleep/wait before continuing

Next Post:

Change navbar color in Twitter Bootstrap

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error