Java replace a file


















Since this question is pretty specific, I'll add a more general solution here for future readers based on the title. Basically you read the whole file to a List , edit the list and finally write the list back to file.

This is the best you can get, with constraints of your question. However, at least the example in question is replacing string of same length, So the second way should work. Also be aware: Java strings are Unicode text, while text files are bytes with some encoding. I was going to answer this question.

Then I saw it get marked as a duplicate of this question, after I'd written the code, so I am going to post my solution here. Keeping in mind that you have to re-write the text file.

First I read the entire file, and store it in a string. I then edit the index corresponding to the line that you wish to edit. Once this is done I concatenate all the strings in the array into a single string.

Then I write the new string into the file, which writes over the old content. Don't worry about losing your old content as it has been written again with the edit. Well you would need to get a file with JFileChooser and then read through the lines of the file using a scanner and the hasNext function. Stack Overflow for Teams — Collaborate and share knowledge with a private group. Create a free Team What is Teams? Collectives on Stack Overflow.

Learn more. Asked 8 years, 1 month ago. Active 7 months ago. Viewed k times. How do I replace a line of text found within a text file? I have a string such as: Do the dishes0 And I want to update it with: Do the dishes1 and vise versa How do I accomplish this?

NOT the entire file. Improve this question. Eveno Eveno 1 1 gold badge 3 3 silver badges 5 5 bronze badges. Change the line. I really need some code designed for my specific purpose. I seem to be doing something wrong every time I try. Then I suggest posting the code where you're making this effort and let SO help you figure out what you're doing wrong. It's long gone now. As I've said I've tried many different methods. Storing it in a temporary array.. Well you need to go back to implementing these methods, and when you get stuck, come back here and post that.

Show 2 more comments. Active Oldest Votes. Improve this answer. Michael Yaworski Michael Yaworski Get certified by completing a course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:. Report Error. Your message has been sent to W3Schools.

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. By default, symbolic links are followed and the file attribute of the final target of the link is set. If this method is invoked to set security sensitive attributes then the security manager may be invoked to check for additional permissions.

The attribute parameter identifies the attribute to be read and takes the form: [ view-name : ] attribute-name where square brackets [ If this method is invoked to read security sensitive attributes then the security manager may be invoked to check for additional permissions.

The attributes parameter identifies the attributes to be read and takes the form: [ view-name : ] attribute-list where square brackets [ The attribute-list component is a comma separated list of zero or more names of attributes to 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. 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 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. See Also: FileSystem. Parameters: path - The path to the file Returns: true if the file is a symbolic link; false if the file does not exist, is not a symbolic link, or it cannot be determined if the file is a symbolic link or not.

Throws: SecurityException - In the case of the default provider, and a security manager is installed, its checkRead method denies read access to the file. Parameters: path - the path to the file to test options - options indicating how symbolic links are handled Returns: true if the file is a directory; false if the file does not exist, is not a directory, or it cannot be determined if the file is a directory or not.

Parameters: path - the path to the file options - options indicating how symbolic links are handled Returns: true if the file is a regular file; false if the file does not exist, is not a regular file, or it cannot be determined if the file is a regular file or not. The file time is converted to the epoch and precision supported by the file system. Converting from finer to coarser granularities result in precision loss. The behavior of this method when attempting to set the last modified time when it is not supported by the file system or is outside the range supported by the underlying file store is not defined.

It may or not fail by throwing an IOException. FileTime, java. The size may differ from the actual size on the file system due to compression, support for sparse files, or other reasons. The size of files that are not regular files is implementation specific and therefore unspecified. The options parameter may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. Note that the result of this method is immediately outdated.

If this method indicates the file exists then there is no guarantee that a subsequence access will succeed. Care should be taken when using this method in security sensitive applications. Parameters: path - the path to the file to test options - options indicating how symbolic links are handled.

Returns: true if the file exists; false if the file does not exist or its existence cannot be determined. See Also: notExists java. Path, java. This method is intended for cases where it is required to take action when it can be confirmed that a file does not exist.

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 subsequence attempt to create the file will succeed. Parameters: path - the path to the file to test options - options indicating how symbolic links are handled Returns: true if the file does not exist; false if the file exists or its existence cannot be determined Throws: SecurityException - In the case of the default provider, the SecurityManager.

This method checks that a file exists and that this Java virtual machine has appropriate privileges that would allow it open the file for reading. 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 open the file for reading will succeed or even that it will access the same file.

Parameters: path - the path to the file to check Returns: true if the file exists and is readable; false if the file does not exist, read access would be denied because the Java virtual machine has insufficient privileges, or access cannot be determined Throws: SecurityException - In the case of the default provider, and a security manager is installed, the checkRead is invoked to check read access to the file.

This method checks that a file exists and that this Java virtual machine has appropriate privileges that would allow it open the file for writing. 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.

Parameters: path - the path to the file to check Returns: true if the file exists and is writable; false if the file does not exist, write access would be denied because the Java virtual machine has insufficient privileges, or access cannot be determined Throws: SecurityException - In the case of the default provider, and a security manager is installed, the checkWrite is invoked to check write access to the file.

This method checks that a file exists and that this Java virtual machine has appropriate privileges to execute the file. The semantics may differ when checking access to a directory.

For example, on UNIX systems, checking for execute access checks that the Java virtual machine has permission to search the directory in order to access file or subdirectories. 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. Parameters: path - the path to the file to check Returns: true if the file exists and is executable; false if the file does not exist, execute access would be denied because the Java virtual machine has insufficient privileges, or access cannot be determined Throws: SecurityException - In the case of the default provider, and a security manager is installed, the checkExec is invoked to check execute access to the file.

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. 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. Where the directory is opened successfully, then the entries in the directory, and their descendants are visited. 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.

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. 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.

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. 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.

Parameters: start - the starting file options - options to configure the traversal maxDepth - the maximum number of directory levels to visit visitor - the file visitor to invoke for each file Returns: the starting file Throws: IllegalArgumentException - if the maxDepth parameter is negative SecurityException - If the security manager denies access to the starting file.

In the case of the default provider, the checkRead method is invoked to check read access to the directory. This method works as if invoking it were equivalent to evaluating the expression: walkFileTree start, EnumSet. Parameters: start - the starting file visitor - the file visitor to invoke for each file Returns: the starting file Throws: SecurityException - If the security manager denies access to the starting file.

Bytes from the file are decoded into characters using the specified charset. The Reader methods that read from the file throw IOException if a malformed or unmappable byte sequence is read. See Also: readAllLines java. Bytes from the file are decoded into characters using the UTF-8 charset. This method works as if invoking it were equivalent to evaluating the expression: Files.

The options parameter specifies how the the file is created or opened. The Writer methods to write text throw IOException if the text cannot be encoded using the specified charset. The text is encoded into bytes for writing using the UTF-8 charset. On return, the input stream will be at end of stream. By default, the copy fails if the target file already exists or is a symbolic link. If the target file exists and is a symbolic link, then the symbolic link is replaced. Additional options may be supported in future releases.

Consequently the input stream may not be at end of stream and may be in an inconsistent state. 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.

Consequently the output stream may be in an inconsistent state. 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. 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. Note that this method is intended for simple cases where it is convenient to read all lines in a single operation. See Also: newBufferedReader java. 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. All bytes in the byte array are written to the file. Usage example : By default the method creates a new file or overwrites an existing file.

Each line is a char sequence and is written to the file in sequence with each line terminated by the platform's line separator, as defined by the system property line. Characters are encoded into bytes using the specified charset. Characters are encoded into bytes using the UTF-8 charset. The listing is not recursive.

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 encapsulates a DirectoryStream. If timely disposal of file system resources is required, the try -with-resources construct should be used to ensure that the stream's close method is invoked after the stream operations are completed.

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 file tree is traversed depth-first , the elements in the stream are Path objects that are obtained as if by resolving the relative path against start.

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. 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.

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 encapsulates one or more DirectoryStream s. Operating on a closed stream will result in an IllegalStateException. Parameters: start - the starting file maxDepth - the maximum number of directory levels to visit options - options to configure the traversal Returns: the Stream of Path Throws: IllegalArgumentException - if the maxDepth parameter is negative SecurityException - If the security manager denies access to the starting file.



0コメント

  • 1000 / 1000