Java create new file error

I have a method that writes to a log file. If the file exists it should append to it, if not then I want it to create a new file. if (!file.exists() && !file.createNewFile()) { System....

I have a method that writes to a log file. If the file exists it should append to it, if not then I want it to create a new file.

if (!file.exists() && !file.createNewFile()) {
    System.err.println("Error with output file: " + outFile
        + "nCannot create new file.");
    continue;
}

I have that to check that a file can be created. file is a java.io.File object. createNewFile is throwing an IOException: No such file or directory. This method has been working perfectly since I wrote it a few weeks ago and has only recently starting doing this although I don’t know what I could have changed. I have checked, the directory exists and I have write permissions for it, but then I thought it should just return false if it can’t make the file for any reason.

Is there anything that I am missing to get this working?

asked Oct 6, 2009 at 11:36

A Jackson's user avatar

2

try to ensure the parent directory exists with:

file.getParentFile().mkdirs()

answered Oct 6, 2009 at 11:57

Omry Yadan's user avatar

Omry YadanOmry Yadan

30k18 gold badges63 silver badges85 bronze badges

Perhaps the directory the file is being created in doesn’t exist?

answered Oct 6, 2009 at 11:38

Miserable Variable's user avatar

1

normally this is something you changed recently, first off your sample code is if not file exists and not create new file — you are trying to code away something — what is it?

Then, look at a directory listing to see if it actually exists and do a println / toString() on the file object and getMessage() on the exception, as well as print stack trace.

Then, start from zero knowledge again and re factor from the get-go each step you are using to get here. It’s probably a duh you stuck in there somewhere while conceptualizing in code ( because it was working ) — you just retrace each step in detail, you will find it.

answered Oct 6, 2009 at 12:01

Nicholas Jordan's user avatar

4

I think the exception you get is likely the result from the file check of the atomic method file.createNewFile(). The method can’t check if the file does exist because some of the parent directories do not exist or you have no permissions to access them. I would suggest this:

if (file.getParentFile() != null && !file.getParentFile().mkDirs()) {
    // handle permission problems here
}
// either no parent directories there or we have created missing directories
if (file.createNewFile() || file.isFile()) {
    // ready to write your content
} else {
    // handle directory here
}

If you take concurrency into account, all these checks are useless because in every case some other thread is able to create, delete or do anything else with your file. In this case you have to use file locks which I would not suggest doing ;)

JonyD's user avatar

JonyD

1,1973 gold badges21 silver badges34 bronze badges

answered Oct 6, 2009 at 19:00

According to the [java docs](http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html#createNewFile() ) createNewFile will create a new file atomically for you.

Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist.

Given that createNewFile is atomic and won’t over-write an existing file you can re-write your code as

try {
    if(!file.createNewFile()) {
        System.out.println("File already exists");
    } 
} catch (IOException ex) {
    System.out.println(ex);
}

This may make any potential threading issues, race-conditions, etc, easier to spot.

answered Oct 6, 2009 at 11:54

Glen's user avatar

GlenGlen

21.5k3 gold badges61 silver badges76 bronze badges

1

You are certainly getting this Exception
‘The system cannot find the path specified’

Just print ‘file.getAbsoluteFile()’ , this will let you know what is the file you wanted to create.

This exception will occur if the Directory where you are creating the file doesn’t exist.

answered Oct 6, 2009 at 12:04

Rakesh Juyal's user avatar

Rakesh JuyalRakesh Juyal

35.4k67 gold badges169 silver badges214 bronze badges

1

//Create New File if not present
if (!file.exists()) {
    file.getParentFile().mkdirs();

    file.createNewFile();
    Log.e(TAG, "File Created");
}

Nubok's user avatar

Nubok

3,3926 gold badges27 silver badges46 bronze badges

answered Mar 6, 2020 at 9:39

Ganesan J's user avatar

Ganesan JGanesan J

4737 silver badges11 bronze badges

This could be a threading issue (checking and creating together are not atomic: !file.exists() && !file.createNewFile()) or the «file» is already a directory.

Try (file.isFile()) :

if (file.exists() && !file.isFile()){
   //handle directory is there
}else if(!file.createNewFile()) {
   //as before
}

answered Oct 6, 2009 at 11:42

Thomas Jung's user avatar

Thomas JungThomas Jung

32.1k9 gold badges81 silver badges114 bronze badges

4

In my case was just a lack of permission:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

answered Oct 3, 2016 at 20:22

dianakarenms's user avatar

dianakarenmsdianakarenms

2,5001 gold badge20 silver badges23 bronze badges

Use

yourAppsMainActivityContext.getExternalCacheDir()

instead of

Environment.getExternalStorageDriectory()

to get the file storage path.

Alternatively, you can also try getExternalFilesDir(String type), getExternalCacheDir(), getExternalMediaDirs().

answered Oct 20, 2021 at 21:18

Gene's user avatar

GeneGene

10.6k1 gold badge65 silver badges57 bronze badges

Содержание

  1. Исключение FileNotFoundException в Java
  2. 1. введение
  3. 2. Когда Возникает исключение?
  4. 3. Как с Этим справиться?
  5. 4. Примеры
  6. 4.1. Регистрация исключения
  7. 4.2. Создание исключения для конкретного бизнеса
  8. 4.3. Создание файла
  9. 5. Заключение
  10. java.io.FileNotFoundException in Java
  11. Output
  12. Output
  13. Class Files
  14. Method Summary
  15. Methods declared in class java.lang.Object
  16. Method Details
  17. newInputStream
  18. newOutputStream
  19. newByteChannel
  20. newByteChannel
  21. newDirectoryStream
  22. newDirectoryStream
  23. newDirectoryStream
  24. createFile
  25. createDirectory
  26. createDirectories
  27. createTempFile
  28. createTempFile
  29. createTempDirectory
  30. createTempDirectory
  31. createSymbolicLink
  32. createLink
  33. delete
  34. deleteIfExists
  35. readSymbolicLink
  36. getFileStore
  37. isSameFile
  38. mismatch
  39. isHidden
  40. probeContentType
  41. getFileAttributeView
  42. readAttributes
  43. setAttribute
  44. getAttribute
  45. readAttributes
  46. getPosixFilePermissions
  47. setPosixFilePermissions
  48. getOwner
  49. setOwner
  50. isSymbolicLink
  51. isDirectory
  52. isRegularFile
  53. getLastModifiedTime
  54. setLastModifiedTime
  55. exists
  56. notExists
  57. isReadable
  58. isWritable
  59. isExecutable
  60. walkFileTree
  61. walkFileTree
  62. newBufferedReader
  63. newBufferedReader
  64. newBufferedWriter
  65. newBufferedWriter
  66. readAllBytes
  67. readString
  68. readString
  69. readAllLines
  70. readAllLines
  71. write
  72. write
  73. write
  74. writeString
  75. writeString
  76. lines
  77. lines

Исключение FileNotFoundException в Java

Краткое и практическое руководство по FileNotFoundException в Java.

Автор: baeldung
Дата записи

1. введение

В этой статье мы поговорим об очень распространенном исключении в Java – исключении FileNotFoundException .

Мы рассмотрим случаи, когда это может произойти, возможные способы лечения и некоторые примеры.

2. Когда Возникает исключение?

Как указано в документации API Java, это исключение может быть вызвано, когда:

  • Файл с указанным именем пути не существуетне существует
  • Файл с указанным именем пути существует , но недоступен по какой-либо причине (запрошена запись для файла только для чтения или разрешения не позволяют получить доступ к файлу)

3. Как с Этим справиться?

Прежде всего, принимая во внимание, что он расширяет java.io.IOException , который расширяет java.lang.Исключение , вам нужно будет справиться с ним с помощью блока try-catch , как и с любым другим проверенным E xception .

Затем, что делать (связано с бизнесом/логикой) внутри блока try-catch на самом деле зависит от того, что вам нужно сделать.

Возможно, вам это понадобится:

  • Создание исключения для конкретного бизнеса: это может быть ошибка stopexecutionerror, но вы оставите решение в верхних слоях приложения (не забудьте включить исходное исключение)
  • Предупредите пользователя диалогом или сообщением об ошибке: это не ошибка stopexecutionerror, поэтому достаточно просто уведомить
  • Создание файла: чтение необязательного файла конфигурации, его поиск и создание нового файла со значениями по умолчанию
  • Создайте файл по другому пути: вам нужно что-то написать, и если первый путь недоступен, попробуйте использовать отказоустойчивый
  • Просто зарегистрируйте ошибку: эта ошибка не должна останавливать выполнение, но вы регистрируете ее для дальнейшего анализа

4. Примеры

Теперь мы рассмотрим несколько примеров, все из которых будут основаны на следующем тестовом классе:

4.1. Регистрация исключения

Если вы запустите следующий код, он “зарегистрирует” ошибку в консоли:

4.2. Создание исключения для конкретного бизнеса

Далее приведен пример создания исключения для конкретного бизнеса, чтобы ошибка могла быть обработана на верхних уровнях:

4.3. Создание файла

Наконец, мы попытаемся создать файл, чтобы его можно было прочитать (возможно, для потока, который непрерывно читает файл), но снова поймаем исключение и обработаем возможную вторую ошибку:

5. Заключение

В этой быстрой записи мы видели, когда может возникнуть исключение FileNotFoundException и несколько вариантов его обработки.

Как всегда, полные примеры находятся на Github .

Источник

java.io.FileNotFoundException in Java

java.io.FileNotFoundException which is a common exception which occurs while we try to access a file. FileNotFoundExcetion is thrown by constructors RandomAccessFile, FileInputStream, and FileOutputStream. FileNotFoundException occurs at runtime so it is a checked exception, we can handle this exception by java code, and we have to take care of the code so that this exception doesn’t occur.

Declaration :

Constructors :

  • FileNotFoundException() : It gives FileNotFoundException with null message.
  • FileNotFoundException(String s) : It gives FileNotFoundException with detail message.

It doesn’t have any methods. Now let’s understand the hierarchy of this class i.e FileNotFoundException extends IOException which further extends the Exception class which extends the Throwable class and further the Object class.

Hierarchy Diagram:

Why this Exception occurs?

There are mainly 2 scenarios when FileNotFoundException occurs. Now let’s see them with examples provided:

  1. If the given file is not available in the given location then this error will occur.
  2. If the given file is inaccessible, for example, if it is read-only then you can read the file but not modify the file, if we try to modify it, an error will occur or if the file that you are trying to access for the read/write operation is opened by another program then this error will occur.

Scenario 1:

If the given file is not available in the given location then this error will occur.

Example:

Output

Scenario 2:

If the given file is inaccessible, for example, if it is read-only then you can read the file but not modify the file if we try to modify it, an error will occur or if the file that you are trying to access for the read/write operation is opened by another program then this error will occur.

Example:

Output

Handling Exception:

Firstly we have to use the try-catch block if we know whether the error will occur. Inside try block all the lines should be there if there are chances of errors. There are other remedies to handle the exception:

  1. If the message of the exception tells that there is no such file or directory, then you re-verify whether you mentioned the wrong file name in the program or file exists in that directory or not.
  2. If the message of the exception tells us that access is denied then we have to check the permissions of the file (read, write, both read and write) and also check whether that file is in use by another program.
  3. If the message of the exception tells us that the specified file is a directory then you must either delete the existing directory(if the directory not in use) or change the name of the file.

Источник

Class Files

In most cases, the methods defined here will delegate to the associated file system provider to perform the file operations.

Method Summary

Methods declared in class java.lang.Object

Method Details

newInputStream

The options parameter determines how the file is opened. If no options are present then it is equivalent to opening the file with the READ option. In addition to the READ option, an implementation may also support additional implementation specific options.

newOutputStream

This method opens or creates a file in exactly the manner specified by the newByteChannel method with the exception that the READ option may not be present in the array of options. If no options are present then this method works as if the CREATE , TRUNCATE_EXISTING , and WRITE options are present. In other words, it opens the file for writing, creating the file if it doesn’t exist, or initially truncating an existing regular-file to a size of 0 if it exists.

newByteChannel

The options parameter determines how the file is opened. The READ and WRITE options determine if the file should be opened for reading and/or writing. If neither option (or the APPEND option) is present then the file is opened for reading. By default reading or writing commence at the beginning of the file.

In the addition to READ and WRITE , the following options may be present:

Options

Option Description
APPEND If this option is present then the file is opened for writing and each invocation of the channel’s write method first advances the position to the end of the file and then writes the requested data. Whether the advancement of the position and the writing of the data are done in a single atomic operation is system-dependent and therefore unspecified. This option may not be used in conjunction with the READ or TRUNCATE_EXISTING options.
TRUNCATE_EXISTING If this option is present then the existing file is truncated to a size of 0 bytes. This option is ignored when the file is opened only for reading.
CREATE_NEW If this option is present then a new file is created, failing if the file already exists or is a symbolic link. When creating a file the check for the existence of the file and the creation of the file if it does not exist is atomic with respect to other file system operations. This option is ignored when the file is opened only for reading.
CREATE If this option is present then an existing file is opened if it exists, otherwise a new file is created. This option is ignored if the CREATE_NEW option is also present or the file is opened only for reading.
DELETE_ON_CLOSE When this option is present then the implementation makes a best effort attempt to delete the file when closed by the close method. If the close method is not invoked then a best effort attempt is made to delete the file when the Java virtual machine terminates.
SPARSE When creating a new file this option is a hint that the new file will be sparse. This option is ignored when not creating a new file.
SYNC Requires that every update to the file’s content or metadata be written synchronously to the underlying storage device. (see Synchronized I/O file integrity).
DSYNC Requires that every update to the file’s content be written synchronously to the underlying storage device. (see Synchronized I/O file integrity).

An implementation may also support additional implementation specific options.

The attrs parameter is optional file-attributes to set atomically when a new file is created.

In the case of the default provider, the returned seekable byte channel is a FileChannel .

newByteChannel

This method opens or creates a file in exactly the manner specified by the newByteChannel method.

newDirectoryStream

When not using the try-with-resources construct, then directory stream’s close method should be invoked after iteration is completed so as to free any resources held for the open directory.

When an implementation supports operations on entries in the directory that execute in a race-free manner then the returned directory stream is a SecureDirectoryStream .

newDirectoryStream

For example, suppose we want to iterate over the files ending with «.java» in a directory:

The globbing pattern is specified by the getPathMatcher method.

When not using the try-with-resources construct, then directory stream’s close method should be invoked after iteration is completed so as to free any resources held for the open directory.

When an implementation supports operations on entries in the directory that execute in a race-free manner then the returned directory stream is a SecureDirectoryStream .

newDirectoryStream

When not using the try-with-resources construct, then directory stream’s close method should be invoked after iteration is completed so as to free any resources held for the open directory.

Where the filter terminates due to an uncaught error or runtime exception then it is propagated to the hasNext or next method. Where an IOException is thrown, it results in the hasNext or next method throwing a DirectoryIteratorException with the IOException as the cause.

When an implementation supports operations on entries in the directory that execute in a race-free manner then the returned directory stream is a SecureDirectoryStream .

Usage Example: Suppose we want to iterate over the files in a directory that are larger than 8K.

createFile

The attrs parameter is optional file-attributes to set atomically when creating the file. Each attribute is identified by its name . If more than one attribute of the same name is included in the array then all but the last occurrence is ignored.

createDirectory

The attrs parameter is optional file-attributes to set atomically when creating the directory. Each attribute is identified by its name . If more than one attribute of the same name is included in the array then all but the last occurrence is ignored.

createDirectories

The attrs parameter is optional file-attributes to set atomically when creating the nonexistent directories. Each file attribute is identified by its name . If more than one attribute of the same name is included in the array then all but the last occurrence is ignored.

If this method fails, then it may do so after creating some, but not all, of the parent directories.

createTempFile

The details as to how the name of the file is constructed is implementation dependent and therefore not specified. Where possible the prefix and suffix are used to construct candidate names in the same manner as the File.createTempFile(String,String,File) method.

As with the File.createTempFile methods, this method is only part of a temporary-file facility. Where used as a work files, the resulting file may be opened using the DELETE_ON_CLOSE option so that the file is deleted when the appropriate close method is invoked. Alternatively, a shutdown-hook , or the File.deleteOnExit() mechanism may be used to delete the file automatically.

The attrs parameter is optional file-attributes to set atomically when creating the file. Each attribute is identified by its name . If more than one attribute of the same name is included in the array then all but the last occurrence is ignored. When no file attributes are specified, then the resulting file may have more restrictive access permissions to files created by the File.createTempFile(String,String,File) method.

createTempFile

This method works in exactly the manner specified by the createTempFile(Path,String,String,FileAttribute[]) method for the case that the dir parameter is the temporary-file directory.

createTempDirectory

The details as to how the name of the directory is constructed is implementation dependent and therefore not specified. Where possible the prefix is used to construct candidate names.

As with the createTempFile methods, this method is only part of a temporary-file facility. A shutdown-hook , or the File.deleteOnExit() mechanism may be used to delete the directory automatically.

The attrs parameter is optional file-attributes to set atomically when creating the directory. Each attribute is identified by its name . If more than one attribute of the same name is included in the array then all but the last occurrence is ignored.

createTempDirectory

This method works in exactly the manner specified by createTempDirectory(Path,String,FileAttribute[]) method for the case that the dir parameter is the temporary-file directory.

createSymbolicLink

The target parameter is the target of the link. It may be an absolute or relative path and may not exist. When the target is a relative path then file system operations on the resulting link are relative to the path of the link.

The attrs parameter is optional attributes to set atomically when creating the link. Each attribute is identified by its name . If more than one attribute of the same name is included in the array then all but the last occurrence is ignored.

Where symbolic links are supported, but the underlying FileStore does not support symbolic links, then this may fail with an IOException . Additionally, some operating systems may require that the Java virtual machine be started with implementation specific privileges to create symbolic links, in which case this method may throw IOException .

createLink

The link parameter locates the directory entry to create. The existing parameter is the path to an existing file. This method creates a new directory entry for the file so that it can be accessed using link as the path. On some file systems this is known as creating a «hard link». Whether the file attributes are maintained for the file or for each directory entry is file system specific and therefore not specified. Typically, a file system requires that all links (directory entries) for a file be on the same file system. Furthermore, on some platforms, the Java virtual machine may require to be started with implementation specific privileges to create hard links or to create links to directories.

delete

An implementation may require to examine the file to determine if the file is a directory. Consequently this method may not be atomic with respect to other file system operations. If the file is a symbolic link then the symbolic link itself, not the final target of the link, is deleted.

If the file is a directory then the directory must be empty. In some implementations a directory has entries for special files or links that are created when the directory is created. In such implementations a directory is considered empty when only the special entries exist. This method can be used with the walkFileTree method to delete a directory and all entries in the directory, or an entire file-tree where required.

On some operating systems it may not be possible to remove a file when it is open and in use by this Java virtual machine or other programs.

deleteIfExists

As with the delete(Path) method, an implementation may need to examine the file to determine if the file is a directory. Consequently this method may not be atomic with respect to other file system operations. If the file is a symbolic link, then the symbolic link itself, not the final target of the link, is deleted.

If the file is a directory then the directory must be empty. In some implementations a directory has entries for special files or links that are created when the directory is created. In such implementations a directory is considered empty when only the special entries exist.

On some operating systems it may not be possible to remove a file when it is open and in use by this Java virtual machine or other programs.

This method copies a file to the target file with the options parameter specifying how the copy is performed. By default, the copy fails if the target file already exists or is a symbolic link, except if the source and target are the same file, in which case the method completes without copying the file. File attributes are not required to be copied to the target file. If symbolic links are supported, and the file is a symbolic link, then the final target of the link is copied. If the file is a directory then it creates an empty directory in the target location (entries in the directory are not copied). This method can be used with the walkFileTree method to copy a directory and all entries in the directory, or an entire file-tree where required.

The options parameter may include any of the following:

Options

Option Description
REPLACE_EXISTING If the target file exists, then the target file is replaced if it is not a non-empty directory. If the target file exists and is a symbolic link, then the symbolic link itself, not the target of the link, is replaced.
COPY_ATTRIBUTES Attempts to copy the file attributes associated with this file to the target file. The exact file attributes that are copied is platform and file system dependent and therefore unspecified. Minimally, the last-modified-time is copied to the target file if supported by both the source and target file stores. Copying of file timestamps may result in precision loss.
NOFOLLOW_LINKS Symbolic links are not followed. If the file is a symbolic link, then the symbolic link itself, not the target of the link, is copied. It is implementation specific if file attributes can be copied to the new link. In other words, the COPY_ATTRIBUTES option may be ignored when copying a symbolic link.

An implementation of this interface may support additional implementation specific options.

Copying a file is not an atomic operation. If an IOException is thrown, then it is possible that the target file is incomplete or some of its file attributes have not been copied from the source file. When the REPLACE_EXISTING option is specified and the target file exists, then the target file is replaced. The check for the existence of the file and the creation of the new file may not be atomic with respect to other file system activities.

Usage Example: Suppose we want to copy a file into a directory, giving it the same file name as the source file:

By default, this method attempts to move the file to the target file, failing if the target file exists except if the source and target are the same file, in which case this method has no effect. If the file is a symbolic link then the symbolic link itself, not the target of the link, is moved. This method may be invoked to move an empty directory. In some implementations a directory has entries for special files or links that are created when the directory is created. In such implementations a directory is considered empty when only the special entries exist. When invoked to move a directory that is not empty then the directory is moved if it does not require moving the entries in the directory. For example, renaming a directory on the same FileStore will usually not require moving the entries in the directory. When moving a directory requires that its entries be moved then this method fails (by throwing an IOException ). To move a file tree may involve copying rather than moving directories and this can be done using the copy method in conjunction with the Files.walkFileTree utility method.

The options parameter may include any of the following:

Options

Option Description
REPLACE_EXISTING If the target file exists, then the target file is replaced if it is not a non-empty directory. If the target file exists and is a symbolic link, then the symbolic link itself, not the target of the link, is replaced.
ATOMIC_MOVE The move is performed as an atomic file system operation and all other options are ignored. If the target file exists then it is implementation specific if the existing file is replaced or this method fails by throwing an IOException . If the move cannot be performed as an atomic file system operation then AtomicMoveNotSupportedException is thrown. This can arise, for example, when the target location is on a different FileStore and would require that the file be copied, or target location is associated with a different provider to this object.

An implementation of this interface may support additional implementation specific options.

Moving a file will copy the last-modified-time to the target file if supported by both source and target file stores. Copying of file timestamps may result in precision loss. An implementation may also attempt to copy other file attributes but is not required to fail if the file attributes cannot be copied. When the move is performed as a non-atomic operation, and an IOException is thrown, then the state of the files is not defined. The original file and the target file may both exist, the target file may be incomplete or some of its file attributes may not been copied from the original file.

Usage Examples: Suppose we want to rename a file to «newname», keeping the file in the same directory: Alternatively, suppose we want to move a file to new directory, keeping the same file name, and replacing any existing file of that name in the directory:

readSymbolicLink

If the file system supports symbolic links then this method is used to read the target of the link, failing if the file is not a symbolic link. The target of the link need not exist. The returned Path object will be associated with the same file system as link .

getFileStore

Once a reference to the FileStore is obtained it is implementation specific if operations on the returned FileStore , or FileStoreAttributeView objects obtained from it, continue to depend on the existence of the file. In particular the behavior is not defined for the case that the file is deleted or moved to a different file store.

isSameFile

If both Path objects are equal then this method returns true without checking if the file exists. If the two Path objects are associated with different providers then this method returns false . Otherwise, this method checks if both Path objects locate the same file, and depending on the implementation, may require to open or access both files.

If the file system and files remain static, then this method implements an equivalence relation for non-null Paths .

  • It is reflexive: for Path f , isSameFile(f,f) should return true .
  • It is symmetric: for two Paths f and g , isSameFile(f,g) will equal isSameFile(g,f) .
  • It is transitive: for three Paths f , g , and h , if isSameFile(f,g) returns true and isSameFile(g,h) returns true , then isSameFile(f,h) will return true .

mismatch

Two files are considered to match if they satisfy one of the following conditions:

  • The two paths locate the same file, even if two equal paths locate a file does not exist, or
  • The two files are the same size, and every byte in the first file is identical to the corresponding byte in the second file.

Otherwise there is a mismatch between the two files and the value returned by this method is:

  • The position of the first mismatched byte, or
  • The size of the smaller file (in bytes) when the files are different sizes and every byte of the smaller file is identical to the corresponding byte of the larger file.

This method may not be atomic with respect to other file system operations. This method is always reflexive (for Path f , mismatch(f,f) returns -1L ). If the file system and files remain static, then this method is symmetric (for two Paths f and g , mismatch(f,g) will return the same value as mismatch(g,f) ).

isHidden

Depending on the implementation this method may require to access the file system to determine if the file is considered hidden.

Parameters: path — the path to the file to test Returns: true if the file is considered hidden Throws: IOException — if an I/O error occurs SecurityException — In the case of the default provider, and a security manager is installed, the checkRead method is invoked to check read access to the file.

probeContentType

This method uses the installed FileTypeDetector implementations to probe the given file to determine its content type. Each file type detector’s probeContentType is invoked, in turn, to probe the file type. If the file is recognized then the content type is returned. If the file is not recognized by any of the installed file type detectors then a system-default file type detector is invoked to guess the content type.

A given invocation of the Java virtual machine maintains a system-wide list of file type detectors. Installed file type detectors are loaded using the service-provider loading facility defined by the ServiceLoader class. Installed file type detectors are loaded using the system class loader. If the system class loader cannot be found then the platform class loader is used. File type detectors are typically installed by placing them in a JAR file on the application class path, the JAR file contains a provider-configuration file named java.nio.file.spi.FileTypeDetector in the resource directory META-INF/services , and the file lists one or more fully-qualified names of concrete subclass of FileTypeDetector that have a zero argument constructor. If the process of locating or instantiating the installed file type detectors fails then an unspecified error is thrown. The ordering that installed providers are located is implementation specific.

The return value of this method is the string form of the value of a Multipurpose Internet Mail Extension (MIME) content type as defined by RFC 2045: Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies. The string is guaranteed to be parsable according to the grammar in the RFC.

getFileAttributeView

A file attribute view provides a read-only or updatable view of a set of file attributes. This method is intended to be used where the file attribute view defines type-safe methods to read or update the file attributes. The type parameter is the type of the attribute view required and the method returns an instance of that type if supported. The BasicFileAttributeView type supports access to the basic attributes of a file. Invoking this method to select a file attribute view of that type will always return an instance of that class.

The options array may be used to indicate how symbolic links are handled by the resulting file attribute view for the case that the file is a symbolic link. By default, symbolic links are followed. If the option NOFOLLOW_LINKS is present then symbolic links are not followed. This option is ignored by implementations that do not support symbolic links.

Usage Example: Suppose we want read or set a file’s ACL, if supported:

readAttributes

The type parameter is the type of the attributes required and this method returns an instance of that type if supported. All implementations support a basic set of file attributes and so invoking this method with a type parameter of BasicFileAttributes.class will not throw UnsupportedOperationException .

The options array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.

It is implementation specific if all file attributes are read as an atomic operation with respect to other file system operations.

Usage Example: Suppose we want to read a file’s attributes in bulk: Alternatively, suppose we want to read file’s POSIX attributes without following symbolic links:

setAttribute

The attribute parameter identifies the attribute to be set and takes the form:

view-name is the name of a FileAttributeView that identifies a set of file attributes. If not specified then it defaults to «basic» , the name of the file attribute view that identifies the basic set of file attributes common to many file systems. attribute-name is the name of the attribute within the set.

The options array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is set. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.

Usage Example: Suppose we want to set the DOS «hidden» attribute:

getAttribute

The attribute parameter identifies the attribute to be read and takes the form:

view-name is the name of a FileAttributeView that identifies a set of file attributes. If not specified then it defaults to «basic» , the name of the file attribute view that identifies the basic set of file attributes common to many file systems. attribute-name is the name of the attribute.

The options array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.

Usage Example: Suppose we require the user ID of the file owner on a system that supports a » unix » view:

readAttributes

The attributes parameter identifies the attributes to be read and takes the form:

view-name is the name of a FileAttributeView that identifies a set of file attributes. If not specified then it defaults to «basic» , the name of the file attribute view that identifies the basic set of file attributes common to many file systems.

The attribute-list component is a comma separated list of one or more names of attributes to read. If the list contains the value «*» then all attributes are read. Attributes that are not supported are ignored and will not be present in the returned map. It is implementation specific if all attributes are read as an atomic operation with respect to other file system operations.

The following examples demonstrate possible values for the attributes parameter:

Possible values

Example Description
«*» Read all basic-file-attributes .
«size,lastModifiedTime,lastAccessTime» Reads the file size, last modified time, and last access time attributes.
«posix:*» Read all POSIX-file-attributes .
«posix:permissions,owner,size» Reads the POSIX file permissions, owner, and file size.

The options array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.

getPosixFilePermissions

The path parameter is associated with a FileSystem that supports the PosixFileAttributeView . This attribute view provides access to file attributes commonly associated with files on file systems used by operating systems that implement the Portable Operating System Interface (POSIX) family of standards.

The options array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.

setPosixFilePermissions

The path parameter is associated with a FileSystem that supports the PosixFileAttributeView . This attribute view provides access to file attributes commonly associated with files on file systems used by operating systems that implement the Portable Operating System Interface (POSIX) family of standards.

getOwner

The path parameter is associated with a file system that supports FileOwnerAttributeView . This file attribute view provides access to a file attribute that is the owner of the file.

setOwner

The path parameter is associated with a file system that supports FileOwnerAttributeView . This file attribute view provides access to a file attribute that is the owner of the file.

Usage Example: Suppose we want to make «joe» the owner of a file:

isSymbolicLink

Where it is required to distinguish an I/O exception from the case that the file is not a symbolic link then the file attributes can be read with the readAttributes method and the file type tested with the BasicFileAttributes.isSymbolicLink() method.

isDirectory

The options array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.

Where it is required to distinguish an I/O exception from the case that the file is not a directory then the file attributes can be read with the readAttributes method and the file type tested with the BasicFileAttributes.isDirectory() method.

isRegularFile

The options array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.

Where it is required to distinguish an I/O exception from the case that the file is not a regular file then the file attributes can be read with the readAttributes method and the file type tested with the BasicFileAttributes.isRegularFile() method.

getLastModifiedTime

The options array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.

setLastModifiedTime

Usage Example: Suppose we want to set the last modified time to the current time:

exists

The options parameter may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.

Note that the result of this method is immediately outdated. If this method indicates the file exists then there is no guarantee that a subsequent access will succeed. Care should be taken when using this method in security sensitive applications.

notExists

The options parameter may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.

Note that this method is not the complement of the exists method. Where it is not possible to determine if a file exists or not then both methods return false . As with the exists method, the result of this method is immediately outdated. If this method indicates the file does exist then there is no guarantee that a subsequent attempt to create the file will succeed. Care should be taken when using this method in security sensitive applications.

isReadable

Note that the result of this method is immediately outdated, there is no guarantee that a subsequent attempt to open the file for reading will succeed (or even that it will access the same file). Care should be taken when using this method in security sensitive applications.

isWritable

Note that result of this method is immediately outdated, there is no guarantee that a subsequent attempt to open the file for writing will succeed (or even that it will access the same file). Care should be taken when using this method in security sensitive applications.

isExecutable

Depending on the implementation, this method may require to read file permissions, access control lists, or other file attributes in order to check the effective access to the file. Consequently, this method may not be atomic with respect to other file system operations.

Note that the result of this method is immediately outdated, there is no guarantee that a subsequent attempt to execute the file will succeed (or even that it will access the same file). Care should be taken when using this method in security sensitive applications.

walkFileTree

This method walks a file tree rooted at a given starting file. The file tree traversal is depth-first with the given FileVisitor invoked for each file encountered. File tree traversal completes when all accessible files in the tree have been visited, or a visit method returns a result of TERMINATE . Where a visit method terminates due an IOException , an uncaught error, or runtime exception, then the traversal is terminated and the error or exception is propagated to the caller of this method.

For each file encountered this method attempts to read its BasicFileAttributes . If the file is not a directory then the visitFile method is invoked with the file attributes. If the file attributes cannot be read, due to an I/O exception, then the visitFileFailed method is invoked with the I/O exception.

Where the file is a directory, and the directory could not be opened, then the visitFileFailed method is invoked with the I/O exception, after which, the file tree walk continues, by default, at the next sibling of the directory.

Where the directory is opened successfully, then the entries in the directory, and their descendants are visited. When all entries have been visited, or an I/O error occurs during iteration of the directory, then the directory is closed and the visitor’s postVisitDirectory method is invoked. The file tree walk then continues, by default, at the next sibling of the directory.

By default, symbolic links are not automatically followed by this method. If the options parameter contains the FOLLOW_LINKS option then symbolic links are followed. When following links, and the attributes of the target cannot be read, then this method attempts to get the BasicFileAttributes of the link. If they can be read then the visitFile method is invoked with the attributes of the link (otherwise the visitFileFailed method is invoked as specified above).

If the options parameter contains the FOLLOW_LINKS option then this method keeps track of directories visited so that cycles can be detected. A cycle arises when there is an entry in a directory that is an ancestor of the directory. Cycle detection is done by recording the file-key of directories, or if file keys are not available, by invoking the isSameFile method to test if a directory is the same file as an ancestor. When a cycle is detected it is treated as an I/O error, and the visitFileFailed method is invoked with an instance of FileSystemLoopException .

The maxDepth parameter is the maximum number of levels of directories to visit. A value of 0 means that only the starting file is visited, unless denied by the security manager. A value of MAX_VALUE may be used to indicate that all levels should be visited. The visitFile method is invoked for all files, including directories, encountered at maxDepth , unless the basic file attributes cannot be read, in which case the visitFileFailed method is invoked.

If a visitor returns a result of null then NullPointerException is thrown.

When a security manager is installed and it denies access to a file (or directory), then it is ignored and the visitor is not invoked for that file (or directory).

walkFileTree

This method works as if invoking it were equivalent to evaluating the expression:

newBufferedReader

The Reader methods that read from the file throw IOException if a malformed or unmappable byte sequence is read.

newBufferedReader

This method works as if invoking it were equivalent to evaluating the expression:

newBufferedWriter

The Writer methods to write text throw IOException if the text cannot be encoded using the specified charset.

newBufferedWriter

This method works as if invoking it were equivalent to evaluating the expression:

By default, the copy fails if the target file already exists or is a symbolic link. If the REPLACE_EXISTING option is specified, and the target file already exists, then it is replaced if it is not a non-empty directory. If the target file exists and is a symbolic link, then the symbolic link is replaced. In this release, the REPLACE_EXISTING option is the only option required to be supported by this method. Additional options may be supported in future releases.

If an I/O error occurs reading from the input stream or writing to the file, then it may do so after the target file has been created and after some bytes have been read or written. Consequently the input stream may not be at end of stream and may be in an inconsistent state. It is strongly recommended that the input stream be promptly closed if an I/O error occurs.

This method may block indefinitely reading from the input stream (or writing to the file). The behavior for the case that the input stream is asynchronously closed or the thread interrupted during the copy is highly input stream and file system provider specific and therefore not specified.

Usage example: Suppose we want to capture a web page and save it to a file:

If an I/O error occurs reading from the file or writing to the output stream, then it may do so after some bytes have been read or written. Consequently the output stream may be in an inconsistent state. It is strongly recommended that the output stream be promptly closed if an I/O error occurs.

This method may block indefinitely writing to the output stream (or reading from the file). The behavior for the case that the output stream is asynchronously closed or the thread interrupted during the copy is highly output stream and file system provider specific and therefore not specified.

Note that if the given output stream is Flushable then its flush method may need to invoked after this method completes so as to flush any buffered output.

readAllBytes

Note that this method is intended for simple cases where it is convenient to read all bytes into a byte array. It is not intended for reading in large files.

readString

readString

This method reads all content including the line separators in the middle and/or at the end. The resulting string will contain line separators as they appear in the file.

readAllLines

This method recognizes the following as line terminators:

  • u000D followed by u000A , CARRIAGE RETURN followed by LINE FEED
  • u000A , LINE FEED
  • u000D , CARRIAGE RETURN

Additional Unicode line terminators may be recognized in future releases.

Note that this method is intended for simple cases where it is convenient to read all lines in a single operation. It is not intended for reading in large files.

readAllLines

This method works as if invoking it were equivalent to evaluating the expression:

write

Usage example: By default the method creates a new file or overwrites an existing file. Suppose you instead want to append bytes to an existing file:

write

The options parameter specifies how the file is created or opened. If no options are present then this method works as if the CREATE , TRUNCATE_EXISTING , and WRITE options are present. In other words, it opens the file for writing, creating the file if it doesn’t exist, or initially truncating an existing regular-file to a size of 0 . The method ensures that the file is closed when all lines have been written (or an I/O error or other runtime exception is thrown). If an I/O error occurs then it may do so after the file has been created or truncated, or after some bytes have been written to the file.

write

This method works as if invoking it were equivalent to evaluating the expression:

writeString

writeString

All characters are written as they are, including the line separators in the char sequence. No extra characters are added.

The options parameter specifies how the file is created or opened. If no options are present then this method works as if the CREATE , TRUNCATE_EXISTING , and WRITE options are present. In other words, it opens the file for writing, creating the file if it doesn’t exist, or initially truncating an existing regular-file to a size of 0 .

The elements of the stream are Path objects that are obtained as if by resolving the name of the directory entry against dir . Some file systems maintain special links to the directory itself and the directory’s parent directory. Entries representing these links are not included.

The stream is weakly consistent. It is thread safe but does not freeze the directory while iterating, so it may (or may not) reflect updates to the directory that occur after returning from this method.

The returned stream contains a reference to an open directory. The directory is closed by closing the stream.

Operating on a closed stream behaves as if the end of stream has been reached. Due to read-ahead, one or more elements may be returned after the stream has been closed.

If an IOException is thrown when accessing the directory after this method has returned, it is wrapped in an UncheckedIOException which will be thrown from the method that caused the access to take place.

The stream walks the file tree as elements are consumed. The Stream returned is guaranteed to have at least one element, the starting file itself. For each file visited, the stream attempts to read its BasicFileAttributes . If the file is a directory and can be opened successfully, entries in the directory, and their descendants will follow the directory in the stream as they are encountered. When all entries have been visited, then the directory is closed. The file tree walk then continues at the next sibling of the directory.

The stream is weakly consistent. It does not freeze the file tree while iterating, so it may (or may not) reflect updates to the file tree that occur after returned from this method.

By default, symbolic links are not automatically followed by this method. If the options parameter contains the FOLLOW_LINKS option then symbolic links are followed. When following links, and the attributes of the target cannot be read, then this method attempts to get the BasicFileAttributes of the link.

If the options parameter contains the FOLLOW_LINKS option then the stream keeps track of directories visited so that cycles can be detected. A cycle arises when there is an entry in a directory that is an ancestor of the directory. Cycle detection is done by recording the file-key of directories, or if file keys are not available, by invoking the isSameFile method to test if a directory is the same file as an ancestor. When a cycle is detected it is treated as an I/O error with an instance of FileSystemLoopException .

The maxDepth parameter is the maximum number of levels of directories to visit. A value of 0 means that only the starting file is visited, unless denied by the security manager. A value of MAX_VALUE may be used to indicate that all levels should be visited.

When a security manager is installed and it denies access to a file (or directory), then it is ignored and not included in the stream.

The returned stream contains references to one or more open directories. The directories are closed by closing the stream.

If an IOException is thrown when accessing the directory after this method has returned, it is wrapped in an UncheckedIOException which will be thrown from the method that caused the access to take place.

This method works as if invoking it were equivalent to evaluating the expression:

The returned stream contains references to one or more open directories. The directories are closed by closing the stream.

This method walks the file tree in exactly the manner specified by the walk method. For each file encountered, the given BiPredicate is invoked with its Path and BasicFileAttributes . The Path object is obtained as if by resolving the relative path against start and is only included in the returned Stream if the BiPredicate returns true. Compare to calling filter on the Stream returned by walk method, this method may be more efficient by avoiding redundant retrieval of the BasicFileAttributes .

The returned stream contains references to one or more open directories. The directories are closed by closing the stream.

If an IOException is thrown when accessing the directory after returned from this method, it is wrapped in an UncheckedIOException which will be thrown from the method that caused the access to take place.

lines

Bytes from the file are decoded into characters using the specified charset and the same line terminators as specified by readAllLines are supported.

The returned stream contains a reference to an open file. The file is closed by closing the stream.

The file contents should not be modified during the execution of the terminal stream operation. Otherwise, the result of the terminal stream operation is undefined.

After this method returns, then any subsequent I/O exception that occurs while reading from the file or when a malformed or unmappable byte sequence is read, is wrapped in an UncheckedIOException that will be thrown from the Stream method that caused the read to take place. In case an IOException is thrown when closing the file, it is also wrapped as an UncheckedIOException .

For non-line-optimal charsets the stream source’s spliterator has poor splitting properties, similar to that of a spliterator associated with an iterator or that associated with a stream returned from BufferedReader.lines() . Poor splitting properties can result in poor parallel stream performance.

For line-optimal charsets the stream source’s spliterator has good splitting properties, assuming the file contains a regular sequence of lines. Good splitting properties can result in good parallel stream performance. The spliterator for a line-optimal charset takes advantage of the charset properties (a line feed or a carriage return being efficient identifiable) such that when splitting it can approximately divide the number of covered lines in half.

Parameters: path — the path to the file cs — the charset to use for decoding Returns: the lines from the file as a Stream Throws: IOException — if an I/O error occurs opening the file SecurityException — In the case of the default provider, and a security manager is installed, the checkRead method is invoked to check read access to the file. Since: 1.8 See Also:

  • readAllLines(Path, Charset)
  • newBufferedReader(Path, Charset)
  • BufferedReader.lines()

lines

The returned stream contains a reference to an open file. The file is closed by closing the stream.

The file contents should not be modified during the execution of the terminal stream operation. Otherwise, the result of the terminal stream operation is undefined.

This method works as if invoking it were equivalent to evaluating the expression:

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2022, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Источник


posted 8 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

code:

import java.io.*;

class FileWrite

{

public static void main(String args[])

{

try

{

DataInputStream din=new DataInputStream(System.in);

System.out.println(«Enter the name of the new file»);

String filename=din.readLine();

File f=new File(filename);

FileOutputStream fout=new FileOutputStream(f);

DataOutputStream dout=new DataOutputStream(fout);

System.out.println(«enter your name «);

String n=din.readLine();

dout.writeChars(«hello «+ n);

System.out.println(«check your file..»);

}

catch(Exception e)

{}

}

}

error :

d:jpro>javac FileWrite.java

FileWrite.java:11: error: constructor File in class File cannot be applied to given types;

File f=new File(filename);

^

required: no arguments

found: String

reason: actual and formal argument lists differ in length

FileWrite.java:12: error: no suitable constructor found for FileOutputStream(File)

FileOutputStream fout=new FileOutputStream(f);

^

constructor FileOutputStream.FileOutputStream(FileDescriptor) is not applicable

(actual argument File cannot be converted to FileDescriptor by method invocation conversion)

constructor FileOutputStream.FileOutputStream(java.io.File,boolean) is not applicable

(actual and formal argument lists differ in length)

constructor FileOutputStream.FileOutputStream(java.io.File) is not applicable

(actual argument File cannot be converted to java.io.File by method invocation conversion)

constructor FileOutputStream.FileOutputStream(String,boolean) is not applicable

(actual and formal argument lists differ in length)

constructor FileOutputStream.FileOutputStream(String) is not applicable

(actual argument File cannot be converted to String by method invocation conversion)


posted 8 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

simrat khanuja wrote:

There is in fact such a constructor in the File class that is part of core Java — so this error doesn’t make sense.

Do you happen to have your own File class?

Henry

Marshal

Posts: 77298


posted 8 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

You have some potentially dangerous errors in that code. You are creating writers and not closing them (try with resources would be the best way to close them) and you are ignoring a potential Exception.

You mightget no output if you don’t close the writers.

simrat khanuja

Greenhorn

Posts: 12


posted 8 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

no, its not compiling..

this same program has compiled in other IDEs but is failing to compile in cmd.


posted 8 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

simrat khanuja wrote:no, its not compiling..

this same program has compiled in other IDEs but is failing to compile in cmd.

Did you check to see if you happen to have your own File class?

Henry

Master Rancher

Posts: 43045


posted 8 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Something else must be going on — it compiles fine for me on the command line. I agree with Henry — it seems like you have your class called «File» somewhere; is that true? If so, rename it to something that doesn’t clash with the java.io.File class.


posted 8 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

simrat khanuja wrote:

constructor FileOutputStream.FileOutputStream(java.io.File) is not applicable

(actual argument File cannot be converted to java.io.File by method invocation conversion)

More proof. This error is saying that the File class that it found is not the java.io.File class that it was expecting. So, you definitely has a different File class somewhere.

Henry

wood burning stoves

java.io.FileNotFoundException which is a common exception which occurs while we try to access a file. FileNotFoundExcetion is thrown by constructors RandomAccessFile, FileInputStream, and FileOutputStream. FileNotFoundException occurs at runtime so it is a checked exception, we can handle this exception by java code, and we have to take care of the code so that this exception doesn’t occur. 

Declaration : 

public class FileNotFoundException
  extends IOException
    implements ObjectInput, ObjectStreamConstants

Constructors : 

  • FileNotFoundException() : It gives FileNotFoundException with null message.
  • FileNotFoundException(String s) : It gives FileNotFoundException with detail message.

It doesn’t have any methods. Now let’s understand the hierarchy of this class i.e FileNotFoundException extends IOException which further extends the Exception class which extends the Throwable class and further the Object class. 

Hierarchy Diagram:

Why this Exception occurs? 

There are mainly 2 scenarios when FileNotFoundException occurs. Now let’s see them with examples provided:

  1. If the given file is not available in the given location then this error will occur.
  2. If the given file is inaccessible, for example, if it is read-only then you can read the file but not modify the file, if we try to modify it, an error will occur or if the file that you are trying to access for the read/write operation is opened by another program then this error will occur.

Scenario 1:

If the given file is not available in the given location then this error will occur.

Example: 

Java

import java.io.*;

public class Example1 

{

  public static void main(String[] args) 

  {

    FileReader reader = new FileReader("file.txt");

    BufferedReader br = new BufferedReader(reader);

    String data =null;

    while ((data = br.readLine()) != null

    {

        System.out.println(data);

    }

    br.close();

  }

}

Output

prog.java:14: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
    FileReader reader = new FileReader("file.txt");
                        ^
prog.java:25: error: unreported exception IOException; must be caught or declared to be thrown
    while ((data = br.readLine()) != null) 
                              ^
prog.java:31: error: unreported exception IOException; must be caught or declared to be thrown
    br.close();
            ^
3 errors

Scenario 2:

If the given file is inaccessible, for example, if it is read-only then you can read the file but not modify the file if we try to modify it, an error will occur or if the file that you are trying to access for the read/write operation is opened by another program then this error will occur.

Example:

Java

import java.io.*;

import java.util.*;

class Example2 {

  public static void main(String[] args) {

    try {

          File f=new File("file.txt");   

        PrintWriter p1=new PrintWriter(new FileWriter(f), true);

        p1.println("Hello world");

          p1.close();

        f.setReadOnly();

          PrintWriter p2=new PrintWriter(new FileWriter("file.txt"), true);

        p2.println("Hello World");

    }

    catch(Exception ex) {

        ex.printStackTrace();

    }

  }

}

Output

java.security.AccessControlException: access denied ("java.io.FilePermission" "file.txt" "write")
    at java.base/java.security.AccessControlContext.checkPermission(AccessControlContext.java:472)
    at java.base/java.security.AccessController.checkPermission(AccessController.java:897)
    at java.base/java.lang.SecurityManager.checkPermission(SecurityManager.java:322)
    at java.base/java.lang.SecurityManager.checkWrite(SecurityManager.java:752)
    at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:225)
    at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:187)
    at java.base/java.io.FileWriter.<init>(FileWriter.java:96)
    at Example2.main(File.java:19)

Handling Exception:

Firstly we have to use the try-catch block if we know whether the error will occur. Inside try block all the lines should be there if there are chances of errors. There are other remedies to handle the exception:

  1. If the message of the exception tells that there is no such file or directory, then you re-verify whether you mentioned the wrong file name in the program or file exists in that directory or not.
  2. If the message of the exception tells us that access is denied then we have to check the permissions of the file (read, write, both read and write) and also check whether that file is in use by another program.
  3. If the message of the exception tells us that the specified file is a directory then you must either delete the existing directory(if the directory not in use) or change the name of the file.

FileNotFoundException is a checked exception therefore we must catch or handle it. It is a subclass of IOException and is defined in the java.io package. Generally, FileNotFoundException will be thrown by the FileInputStream, FileReader, and RandomAccessFile constructors, where file information is the source and must be passed to the constructor. Here we will discuss the different reasons for getting this exception.

Unhandled exception type FileNotFoundException

FileNotFoundException is a checked exception, and at compile time compiler checks whether we are handling FileNotFoundException or not.

It means if there is a chance to raise FileNotFoundException in the statement then we must handle the FileNotFoundException either by using try-catch block or by using the throws keyword.

Unreported Exception FileNotFoundException; must be caught or declared to be thrown

If we don’t handle FileNotFoundException then the compiler gives the compile-time error: unreported exception FileNotFoundException; must be caught or declared to be thrown.

Example:- FileReader class is used to read character data from the file. The constructor of FileReader class throws FileNotFoundException.

import java.io.FileReader;
public class Test {
   public static void main(String[] args) {
      FileReader fr = new FileReader("data.txt");
      // .......
   }
}

Since we don’t handle FileNotFoundException therefore we will get the compile-time error:- unreported exception FileNotFoundException; must be caught or declared to be thrown,

While compilation,

FileReaderDemo.java:6: error: unreported exception
FileNotFoundException; must be caught or declared to be thrown
FileReader fr = new FileReader(“data.txt”);
^
1 error

Solution of compile-time error: unreported exception FileNotFoundException; must be caught or declared to be thrown,

  • Catch this exception using try/catch block
  • Handle this exception using throws

But before catching and handling the exception we must import FileNotFoundException or java.io package. While catching or handling the exception we can also use superclass exception, Exception, or Throwable. The Throwable is the superclass for all Exceptions.

// Java program to handle the exception
import java.io.FileReader;
import java.io.FileNotFoundException;
public class Test {
   public static void main(String[] args) 
                throws FileNotFoundException {
      FileReader fr = new FileReader("data.txt");
      // .......
   }
}

Using throws we are informing the caller method that the called method may throw FileNotFoundException. Now, it’s the responsibility of the caller method to catch or handle the exception.

import java.io.FileReader;
import java.io.FileNotFoundException;
public class Test {
   public static void main(String[] args) {
      try {
         FileReader fr = new FileReader("data.txt");
         // .......
      } catch (FileNotFoundException fnfe) {
         fnfe.printStackTrace();
      }
   }
}

Using try/catch block we are catching the exception. We can finally block to close the stream also.

Different Reasons to Get FileNotFoundException in Java

We will get runtime exception in the following cases,

  • The passed named File is not available.
  • Available but it is a directory rather than a normal file.
  • The file doesn’t have reading/writing permission.
  • Access permission is not there.

If the given name is a directory/folder, not a file then also we will get the same exception with “Access is denied”.

In all Writer and Output classes, we won’t get FileNotFoundException because the file is not available. These classes are made for writing the data and need destination file information, if the file is not available then their constructors can create an empty file with the given name itself, and then write the data into the file. They are FileNotFoundException for another reason like file creation permission is not there, it is available but represents directory/folder, or file is available but writing permission is not there.

Most of the time, Windows C drive doesn’t allow to create a file, it only gives permission to create a directory. In this case, we can get FileNotFoundException. We can get an exception:- Exception in thread “main” java.io.FileNotFoundException: C:xyz.txt (Access is denied). Similarly, in Linux/Unix OS, we can’t create files in other user directories.

In all Reader and Input classes file is the source from where the Java application will collect the data. And in this case, the file must be available else we will get FileNotFoundException. Other reasons are:- it is a folder rather than a file, access permission is not there.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Понравилась статья? Поделить с друзьями:
  • Java check error type
  • Java centos error could not create the java virtual machine
  • Java exe ошибка приложения
  • Java catch error type
  • Java catch any error