Содержание
- Определение
- Комментарии
- Конструкторы
- Свойства
- Методы
- События
- The FileNotFoundException in Java
- How to deal with the FileNotFoundException
- Download the Eclipse Project
Определение
Это исключение создается, когда попытка доступа к файлу, не существующему на диске, заканчивается неудачей. The exception that is thrown when an attempt to access a file that does not exist on disk fails.
Комментарии
FileNotFoundException использует COR_E_FILENOTFOUND HRESULT, которое имеет значение 0x80070002. FileNotFoundException uses the HRESULT COR_E_FILENOTFOUND which has the value 0x80070002.
Если код не имеет PathDiscovery разрешение, сообщение об ошибке для этого исключения может содержать только имя каталога или файла, а не полные пути. If your code does not have PathDiscovery permission, the error message for this exception may only contain file or directory names instead of fully qualified paths.
Конструкторы
Инициализирует новый экземпляр класса FileNotFoundException со строкой сообщений, настроенной на отображение предоставляемого системой сообщения. Initializes a new instance of the FileNotFoundException class with its message string set to a system-supplied message.
Выполняет инициализацию нового экземпляра класса FileNotFoundException с указанными сведениями о сериализации и контексте. Initializes a new instance of the FileNotFoundException class with the specified serialization and context information.
Инициализирует новый экземпляр класса FileNotFoundException с указанным сообщением об ошибке. Initializes a new instance of the FileNotFoundException class with a specified error message.
Инициализирует новый экземпляр класса FileNotFoundException указанным сообщением об ошибке и ссылкой на внутреннее исключение, вызвавшее данное исключение. Initializes a new instance of the FileNotFoundException class with a specified error message and a reference to the inner exception that is the cause of this exception.
Инициализирует новый экземпляр класса FileNotFoundException с заданным сообщением об ошибке и именем файла, который не удается найти. Initializes a new instance of the FileNotFoundException class with a specified error message, and the file name that cannot be found.
Инициализирует новый экземпляр класса FileNotFoundException с заданным сообщением об ошибке, именем файла, который не удается найти, и ссылкой на внутреннее исключение, являющееся причиной данного исключения. Initializes a new instance of the FileNotFoundException class with a specified error message, the file name that cannot be found, and a reference to the inner exception that is the cause of this exception.
Свойства
Возвращает коллекцию пар ключ/значение, предоставляющие дополнительные сведения об исключении, определяемые пользователем. Gets a collection of key/value pairs that provide additional user-defined information about the exception.
(Унаследовано от Exception)
Возвращает имя файла, который не может быть найден. Gets the name of the file that cannot be found.
Возвращает имя журнала, в котором описано, почему закончилась неудачей загрузка сборки. Gets the log file that describes why loading of an assembly failed.
Получает или задает ссылку на файл справки, связанный с этим исключением. Gets or sets a link to the help file associated with this exception.
(Унаследовано от Exception)
Возвращает или задает HRESULT — кодированное числовое значение, присвоенное определенному исключению. Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.
(Унаследовано от Exception)
Возвращает экземпляр класса Exception, который вызвал текущее исключение. Gets the Exception instance that caused the current exception.
(Унаследовано от Exception)
Возвращает сообщение об ошибке с объяснением причин исключения. Gets the error message that explains the reason for the exception.
Возвращает или задает имя приложения или объекта, вызывавшего ошибку. Gets or sets the name of the application or the object that causes the error.
(Унаследовано от Exception)
Получает строковое представление непосредственных кадров в стеке вызова. Gets a string representation of the immediate frames on the call stack.
(Унаследовано от Exception)
Возвращает метод, создавший текущее исключение. Gets the method that throws the current exception.
(Унаследовано от Exception)
Методы
Определяет, равен ли заданный объект текущему объекту. Determines whether the specified object is equal to the current object.
(Унаследовано от Object)
При переопределении в производном классе возвращает исключение Exception, которое является корневой причиной одного или нескольких последующих исключений. When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.
(Унаследовано от Exception)
Служит хэш-функцией по умолчанию. Serves as the default hash function.
(Унаследовано от Object)
Устанавливает объект SerializationInfo с именем файла и дополнительными сведениями об исключении. Sets the SerializationInfo object with the file name and additional exception information.
Возвращает тип среды выполнения текущего экземпляра. Gets the runtime type of the current instance.
(Унаследовано от Exception)
Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.
(Унаследовано от Object)
Возвращает полное имя данного исключения и, возможно, сообщение об ошибке, имя внутреннего исключения и трассировку стека. Returns the fully qualified name of this exception and possibly the error message, the name of the inner exception, and the stack trace.
События
Возникает, когда исключение сериализовано для создания объекта состояния исключения, содержащего сериализованные данные об исключении. Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception.
Hey this is going to be one of those dumb questions. I am trying to pick up a file on my local system and I keep getting a FileNotFoundException thrown.
Someone set me straight please 🙂
Tried moving the file into the same location as the executing application and did the following:
Then I made a random txt file and parked it there too.. «me.txt»
And it works?! So you thing the file name is the problem?
Posted by: Sotirios-Efstathios Maneas in exceptions March 19th, 2014 0 Views
In this tutorial we will discuss about the FileNotFoundException in Java. This exception is thrown during a failed attempt to open the file denoted by a specified pathname.
Also, this exception can be thrown when an application tries to open a file for writing, but the file is read only, or the permissions of the file do not allow the file to be read by any application.
This exception extends the IOException class, which is the general class of exceptions produced by failed or interrupted I/O operations. Also, it implements the Serializable interface and finally, the FileNotFoundException exists since the first version of Java (1.0).
The FileNotFoundException in Java
The following constructors throw a FileNotFoundException when the specified filename does not exist: FileInputStream , FileOutputStream , and RandomAccessFile . These classes aim to obtain input bytes from a file in a file system, while the former class supports both reading and writing to a random access file.
The following snippet reads all the lines of a file, but if the file does not exist, a FileNotFoundException is thrown.
FileNotFoundExceptionExample.java:
In case the file is missing, the following output is produced:
The following snippet tries to append a string at the end of a file. If the file does not exist, the application creates it. However, if the file cannot be created, is a directory, or the file already exists but its permissions are sufficient for changing its content, a FileNotFoundException is thrown.
FileNotFoundExceptionExample_v2.java:
If the file exists and is a directory, the following exception is thrown:
If the file exists, but it doesn’t have the appropriate permissions for writing, the following exception is thrown:
Finally, the aforementioned exception can occur when the requested file exists, but it is already opened by another application.
How to deal with the FileNotFoundException
- If the message of the exception claims that there is no such file or directory, then you must verify that the specified is correct and actually points to a file or directory that exists in your system.
- If the message of the exception claims that permission is denied then, you must first check if the permissions of the file are correct and second, if the file is currently being used by another application.
- If the message of the exception claims that the specified file is a directory, then you must either alter the name of the file or delete the existing directory (if the directory is not being used by an application).
Important: For those developers that use an IDE to implement their Java applications, the relative path for every file must be specified starting from the level where the src directory of the project resides.
Download the Eclipse Project
The Eclipse project of this example: FileNotFoundExceptionExample.zip
This was a tutorial about the FileNotFoundException in Java.
Источник: