Class FileAccess

java.lang.Object
com.chilkatsoft.chilkat2.ChilkatObject
com.chilkatsoft.chilkat2.FileAccess
All Implemented Interfaces:
AutoCloseable

public class FileAccess extends ChilkatObject
<section class="fileaccess-summary">

Read, write, compare, copy, split, inspect, and manage files and paths.

Chilkat.FileAccess provides general-purpose file-system utilities for applications that need direct control over files, directories, paths, timestamps, and low-level file operations. It can read, write, append, seek, compare, copy, rename, delete, split, reassemble, and inspect files, and also includes helpers for directory operations, path parsing, symbolic links, temporary filenames, block-based reading, fragment scanning, text replacement, and open-file access.

Read and write files

Load or save text and binary files, append data, replace file contents, and work with explicit character encodings when needed.

File management

Copy, rename, delete, compare, split, reassemble, and inspect files using straightforward file-system utility methods.

Directories and paths

Create, remove, check, and work with directories, and use path helpers to extract filenames, extensions, directory names, and related path parts.

Open-file operations

Open files for lower-level reading or writing, seek within files, read blocks, and process large files without loading everything at once.

Timestamps and metadata

Get or set file times, inspect sizes and existence, and use metadata helpers when coordinating file processing workflows.

Special file utilities

Generate temporary filenames, work with symbolic links, scan for byte fragments, and perform text replacement in files.

Common pattern: Use FileAccess for local file-system tasks that are outside the scope of a specific protocol class. It is especially useful for preparing files before upload, saving downloaded data, comparing or splitting files, reading large files in blocks, manipulating paths, or performing small filesystem operations without using platform-specific APIs.

For an extended overview, see FileAccess Class Overview.

</section>

Instances hold a native Chilkat object: close them with ChilkatObject.close() (try-with-resources) when done; an unclosed instance is freed when it becomes unreachable.

See Also:
Online reference
  • Constructor Summary

    Constructors
    Constructor
    Description
    Creates a new FileAccess object.
  • Method Summary

    Modifier and Type
    Method
    Description
    void
    appendAnsi​(String text)
    Appends text to the currently open file after converting the string to the legacy ANSI character encoding used by Chilkat for the platform.
    void
    Appends all bytes contained in bd to the currently open file without text conversion.
    void
    appendSb​(StringBuilder sb, String charset)
    Appends the text contained in sb to the currently open file using the character encoding specified by charset.
    void
    appendText​(String str, String charset)
    Appends str to the currently open file after encoding the text with the character set named by charset, such as utf-8 or iso-8859-1.
    void
    Appends the UTF-16 little-endian byte-order mark to the currently open file.
    void
    Appends the UTF-8 byte-order mark to the currently open file.
    void
    dirAutoCreate​(String filePath)
    Ensures that the directory portion of filePath exists.
    void
    dirCreate​(String dirPath)
    Creates the directory specified by dirPath.
    void
    dirDelete​(String dirPath)
    Deletes the directory specified by dirPath.
    void
    dirEnsureExists​(String dirPath)
    Ensures that the complete directory path dirPath exists, creating missing directories along the path as needed.
    boolean
    dirExists​(String dirPath)
    Returns true if dirPath exists as a directory; otherwise returns false.
    void
    Closes the currently open file and releases its operating-system file handle.
    boolean
    fileContentsEqual​(String filePath1, String filePath2)
    Compares filePath1 and filePath2 byte-for-byte and returns true only when their contents are identical.
    void
    fileCopy​(String existingFilepath, String newFilepath, boolean failIfExists)
    Copies existingFilepath to newFilepath.
    void
    fileDelete​(String filePath)
    Deletes the file specified by filePath.
    boolean
    fileExists​(String filePath)
    Returns true if filePath exists; otherwise returns false.
    int
    Checks whether path exists and returns a three-state result: 1 if it exists, 0 if it does not exist, and -1 if Chilkat could not determine the result because of permissions or another filesystem error.
    void
    fileOpen​(String filePath, long accessMode, long shareMode, long createDisposition, long attributes)
    Windows-specific low-level open. Opens filePath using arguments modeled after the Win32 CreateFile API.
    void
    fileReadBd​(int maxNumBytes, BinData binData)
    Reads up to maxNumBytes bytes from the current file position and appends the bytes to binData.
    void
    fileRename​(String existingFilepath, String newFilepath)
    Renames or moves existingFilepath to newFilepath using the local filesystem.
    void
    fileSeek​(int offset, int origin)
    Moves the current file position by offset bytes relative to origin.
    int
    fileSize​(String filePath)
    Returns the file size in bytes as a signed 32-bit integer.
    long
    fileSize64​(String filePath)
    Returns the size of filePath in bytes as a signed 64-bit integer.
    fileSizeStr​(String filePath)
    Returns the size of filePath in bytes as a decimal string.
    int
    fileType​(String path)
    Examines path and classifies the filesystem entry.
    void
    fileWriteBd​(BinData binData, int offset, int numBytes)
    Writes bytes from binData to the currently open file.
    genBlockId​(int index, int length, String encoding)
    Generates a fixed-width decimal block identifier from index, padded to length characters, and then encodes those bytes using encoding (for example base64, hex, or ascii).
    Returns the current working directory of the calling process.
    Returns the directory portion of path according to Chilkat path-parsing rules.
    boolean
    Returns true when the currently open file is positioned at end-of-file; otherwise returns false.
    Returns the filename extension portion of path, including the leading period.
    Returns the final filename component of path, including its extension.
    Returns the final filename component of path with its extension removed.
    int
    Provides the detailed open-error code from the most recent call to FileOpen, OpenForRead, OpenForWrite, OpenForReadWrite, or OpenForAppend.
    Returns the human-readable message corresponding to FileOpenError for the most recent file-open attempt.
    getFileTimeStr​(String path, int which)
    Returns one file timestamp as an ISO 8601 UTC string in the form YYYY-MM-DDTHH:MM:SSZ.
    boolean
    Windows only. If true, OpenForAppend, OpenForRead, OpenForReadWrite, and OpenForWrite request exclusive access to the file.
    int
    getNumBlocks​(int blockSize)
    Returns how many blockSize-byte blocks are required to cover the currently open file.
    getTempFilename​(String dirPath, String prefix)
    Generates a temporary pathname in dirPath using prefix and a random alphanumeric suffix, in the general form prefix_xxxx.TMP.
    void
    openForAppend​(String filePath)
    Opens filePath for writing at end-of-file.
    void
    openForRead​(String filePath)
    Opens an existing filePath for reading.
    void
    openForReadWrite​(String filePath)
    Opens filePath for both reading and writing.
    void
    openForWrite​(String filePath)
    Opens filePath for writing.
    readBinaryToEncoded​(String filePath, String encoding)
    Reads the entire file at filePath as binary data and returns an encoded textual representation.
    void
    readBlockBd​(int blockIndex, int blockSize, BinData bd)
    Reads the zero-based block blockIndex from the currently open file, using blockSize bytes per block, and appends the bytes to bd.
    readEntireTextFile​(String filePath, String charset)
    Reads the entire file at filePath, decodes its bytes using charset, and returns the resulting text.
    int
    readNextFragment​(boolean startAtBeginning, String beginMarker, String endMarker, String charset, StringBuilder sb)
    Scans the currently open file for the next text fragment beginning with beginMarker and ending with endMarker.
    void
    reassembleFile​(String partsDirPath, String partPrefix, String partExtension, String reassembledFilename)
    Reassembles a file previously divided by SplitFile.
    int
    replaceStrings​(String filePath, String charset, String existingString, String replacementString)
    Reads the file at filePath as text using charset, replaces occurrences of existingString with replacementString, writes the updated text back to the file, and returns the number of replacements made.
    void
    setCurrentDir​(String dirPath)
    Changes the current working directory of the calling process to dirPath.
    void
    setFileTimes​(String filePath, DateTime createTime, DateTime lastAccessTime, DateTime lastModTime)
    Sets the creation, last-access, and last-modified timestamps for filePath from the supplied CkDateTime objects.
    void
    setLastModified​(String filePath, DateTime lastModified)
    Sets the last-modified timestamp of filePath from lastModified.
    void
    setLockFileOnOpen​(boolean value)
    Sets the LockFileOnOpen property; see getLockFileOnOpen().
    void
    splitFile​(String fileToSplit, String partPrefix, String partExtension, int partSize, String destDir)
    Splits fileToSplit into sequential binary parts of up to partSize bytes and writes them to destDir using partPrefix and partExtension.
    void
    symlinkCreate​(String targetPath, String linkPath)
    Creates a symbolic link at linkPath that refers to targetPath.
    symlinkTarget​(String linkPath)
    Returns the resolved target pathname for the symbolic link at linkPath.
    void
    treeDelete​(String path)
    Recursively deletes the directory tree rooted at path, including contained files and subdirectories.
    void
    Truncates the currently open file at the current file position.
    void
    writeEntireTextFile​(String filePath, String textData, String charset, boolean includedPreamble)
    Creates or opens filePath, encodes textData using charset, writes the resulting bytes, and closes the file.

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
  • Constructor Details

    • FileAccess

      public FileAccess()
      Creates a new FileAccess object.
  • Method Details

    • getCurrentDir

      public String getCurrentDir()
      Returns the current working directory of the calling process. Relative file and directory paths are resolved against this process-wide working directory.

      Process-wide setting: The working directory belongs to the process, not to an individual FileAccess object. Changing it can therefore affect relative-path behavior elsewhere in the application.

      Returns:
      the value of the CurrentDir property (read-only)
    • getEndOfFile

      public boolean getEndOfFile()
      Returns true when the currently open file is positioned at end-of-file; otherwise returns false.

      Open-file state: This property applies to the file opened by OpenForRead, OpenForWrite, OpenForReadWrite, OpenForAppend, or FileOpen.

      Returns:
      the value of the EndOfFile property (read-only)
    • getFileOpenError

      public int getFileOpenError()
      Provides the detailed open-error code from the most recent call to FileOpen, OpenForRead, OpenForWrite, OpenForReadWrite, or OpenForAppend.

      Code Meaning

      0 Success; no open error.

      1 Access denied.

      2 File not found.

      3 General, non-specific open error.

      4 File already exists.

      5 The path refers to a directory and the requested access involves writing.

      6 Too many symbolic links were encountered while resolving the path.

      7 The process already has the maximum number of files open.

      8 The pathname is too long.

      9 The system-wide limit on open files has been reached.

      10 The pathname refers to a device special file for which no corresponding device exists.

      11 Insufficient kernel memory was available.

      12 A file was to be created, but the containing device has no space available.

      13 A pathname component expected to be a directory is not a directory.

      14 The regular file is too large to be opened because of an operating-system limitation.

      15 The path is on a read-only filesystem and write access was requested.

      Use with FileOpenErrorMsg: FileOpenError is useful for programmatic handling; FileOpenErrorMsg provides the corresponding human-readable message.

      Returns:
      the value of the FileOpenError property (read-only)
    • getFileOpenErrorMsg

      public String getFileOpenErrorMsg()
      Returns the human-readable message corresponding to FileOpenError for the most recent file-open attempt.
      Returns:
      the value of the FileOpenErrorMsg property (read-only)
    • getLockFileOnOpen

      public boolean getLockFileOnOpen()
      Windows only. If true, OpenForAppend, OpenForRead, OpenForReadWrite, and OpenForWrite request exclusive access to the file. Other processes are prevented from opening the file until FileClose releases the handle. The default is false.

      File sharing: Windows file sharing is established when the file handle is opened. Set this property before calling an OpenFor* method.

      Returns:
      the value of the LockFileOnOpen property
    • setLockFileOnOpen

      public void setLockFileOnOpen​(boolean value)
      Sets the LockFileOnOpen property; see getLockFileOnOpen().
      Parameters:
      value - the new value
    • appendAnsi

      public void appendAnsi​(String text)
      Appends text to the currently open file after converting the string to the legacy ANSI character encoding used by Chilkat for the platform.

      Character encoding: Use AppendText or AppendSb when an explicit encoding such as utf-8 is preferred.

      Parameters:
      text - the text argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • appendBd

      public void appendBd​(BinData bd)
      Appends all bytes contained in bd to the currently open file without text conversion.
      Parameters:
      bd - the bd argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • appendSb

      public void appendSb​(StringBuilder sb, String charset)
      Appends the text contained in sb to the currently open file using the character encoding specified by charset.
      Parameters:
      sb - the sb argument (not null)
      charset - the charset argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • appendText

      public void appendText​(String str, String charset)
      Appends str to the currently open file after encoding the text with the character set named by charset, such as utf-8 or iso-8859-1.
      Parameters:
      str - the str argument (not null)
      charset - the charset argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • appendUnicodeBOM

      public void appendUnicodeBOM()
      Appends the UTF-16 little-endian byte-order mark to the currently open file. The two bytes written are FF FE.

      BOM placement: A BOM normally belongs at the beginning of a text file. This method appends bytes at the current write position, so call it before writing text when creating a new UTF-16LE file.

      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • appendUtf8BOM

      public void appendUtf8BOM()
      Appends the UTF-8 byte-order mark to the currently open file. The three bytes written are EF BB BF.

      UTF-8 BOM: A UTF-8 BOM is optional. Some software uses it as an encoding signature, while other software expects BOM-less UTF-8.

      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • dirAutoCreate

      public void dirAutoCreate​(String filePath)
      Ensures that the directory portion of filePath exists. Any missing parent directories are created; the final path component is treated as a filename and is not created as a directory.

      Difference from DirEnsureExists: Use DirAutoCreate when you have a file path. Use DirEnsureExists when the argument itself is a directory path.

      Parameters:
      filePath - the filePath argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • dirCreate

      public void dirCreate​(String dirPath)
      Creates the directory specified by dirPath. Parent directories must already exist; use DirEnsureExists when missing parent directories should also be created.
      Parameters:
      dirPath - the dirPath argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • dirDelete

      public void dirDelete​(String dirPath)
      Deletes the directory specified by dirPath. The directory must be empty; use TreeDelete to recursively delete a directory and its contents.
      Parameters:
      dirPath - the dirPath argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • dirEnsureExists

      public void dirEnsureExists​(String dirPath)
      Ensures that the complete directory path dirPath exists, creating missing directories along the path as needed.
      Parameters:
      dirPath - the dirPath argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • dirExists

      public boolean dirExists​(String dirPath)
      Returns true if dirPath exists as a directory; otherwise returns false.
      Parameters:
      dirPath - the dirPath argument (not null)
      Returns:
      the result; this method never throws ChilkatException
    • fileClose

      public void fileClose()
      Closes the currently open file and releases its operating-system file handle. Any exclusive lock obtained through LockFileOnOpen is released at this time.
    • fileContentsEqual

      public boolean fileContentsEqual​(String filePath1, String filePath2)
      Compares filePath1 and filePath2 byte-for-byte and returns true only when their contents are identical. File sizes are compared first; when sizes match, the files are compared incrementally rather than being loaded entirely into memory.

      Binary comparison: The comparison is byte-oriented. Text encodings, line-ending conventions, and Unicode normalization are not interpreted or normalized.

      Parameters:
      filePath1 - the filePath1 argument (not null)
      filePath2 - the filePath2 argument (not null)
      Returns:
      the result; this method never throws ChilkatException
    • fileCopy

      public void fileCopy​(String existingFilepath, String newFilepath, boolean failIfExists)
      Copies existingFilepath to newFilepath. If failIfExists is true and the destination already exists, the copy fails instead of overwriting it.
      Parameters:
      existingFilepath - the existingFilepath argument (not null)
      newFilepath - the newFilepath argument (not null)
      failIfExists - the failIfExists argument
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • fileDelete

      public void fileDelete​(String filePath)
      Deletes the file specified by filePath.
      Parameters:
      filePath - the filePath argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • fileExists

      public boolean fileExists​(String filePath)
      Returns true if filePath exists; otherwise returns false. Use FileExists3 when the application must distinguish "does not exist" from "could not determine because of an error."
      Parameters:
      filePath - the filePath argument (not null)
      Returns:
      the result; this method never throws ChilkatException
    • fileExists3

      public int fileExists3​(String path)
      Checks whether path exists and returns a three-state result: 1 if it exists, 0 if it does not exist, and -1 if Chilkat could not determine the result because of permissions or another filesystem error.
      Parameters:
      path - the path argument (not null)
      Returns:
      the result (see ChilkatObject.getLastMethodSuccess() where the description mentions failure)
    • fileOpen

      public void fileOpen​(String filePath, long accessMode, long shareMode, long createDisposition, long attributes)
      Windows-specific low-level open. Opens filePath using arguments modeled after the Win32 CreateFile API. For portable code, prefer OpenForRead, OpenForWrite, OpenForReadWrite, or OpenForAppend.

      Category Common values

      Access GENERIC_READ = 0x80000000, GENERIC_WRITE = 0x40000000

      Sharing FILE_SHARE_READ = 0x1, FILE_SHARE_WRITE = 0x2

      Disposition CREATE_NEW=1, CREATE_ALWAYS=2, OPEN_EXISTING=3, OPEN_ALWAYS=4, TRUNCATE_EXISTING=5

      Open failures: When this method fails, inspect FileOpenError and FileOpenErrorMsg for the reason.

      Parameters:
      filePath - the filePath argument (not null)
      accessMode - the accessMode argument (0 .. 4294967295)
      shareMode - the shareMode argument (0 .. 4294967295)
      createDisposition - the createDisposition argument (0 .. 4294967295)
      attributes - the attributes argument (0 .. 4294967295)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • fileReadBd

      public void fileReadBd​(int maxNumBytes, BinData binData)
      Reads up to maxNumBytes bytes from the current file position and appends the bytes to binData. The file position advances by the number of bytes read.

      Destination behavior: Existing bytes already present in binData are preserved; newly read bytes are appended.

      Parameters:
      maxNumBytes - the maxNumBytes argument
      binData - the binData argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • fileRename

      public void fileRename​(String existingFilepath, String newFilepath)
      Renames or moves existingFilepath to newFilepath using the local filesystem.
      Parameters:
      existingFilepath - the existingFilepath argument (not null)
      newFilepath - the newFilepath argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • fileSeek

      public void fileSeek​(int offset, int origin)
      Moves the current file position by offset bytes relative to origin.

      0 Offset from the beginning of the file.

      1 Offset from the current file position.

      2 Offset from end-of-file; negative offsets are commonly used.

      Random access: Seeking changes where the next read or write occurs; it does not itself read, write, or resize the file.

      Parameters:
      offset - the offset argument
      origin - the origin argument
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • fileSize

      public int fileSize​(String filePath)
      Returns the file size in bytes as a signed 32-bit integer.

      Failure returns 0: If the size cannot be obtained (for example, the file does not exist or cannot be accessed), the return value is 0, which is the same as for an empty file. To detect failure, use FileSizeStr, which fails instead of returning a size, or check first with FileExists3.Large files: A signed 32-bit result cannot represent files larger than approximately 2 GB. Use FileSize64 or FileSizeStr for large files.

      Parameters:
      filePath - the filePath argument (not null)
      Returns:
      the result (see ChilkatObject.getLastMethodSuccess() where the description mentions failure)
    • fileSize64

      public long fileSize64​(String filePath)
      Returns the size of filePath in bytes as a signed 64-bit integer.

      Failure returns 0: If the size cannot be obtained (for example, the file does not exist or cannot be accessed), the return value is 0, which is the same as for an empty file. To detect failure, use FileSizeStr, which fails instead of returning a size, or check first with FileExists3.

      Parameters:
      filePath - the filePath argument (not null)
      Returns:
      the result (see ChilkatObject.getLastMethodSuccess() where the description mentions failure)
    • fileSizeStr

      public String fileSizeStr​(String filePath)
      Returns the size of filePath in bytes as a decimal string. This avoids the range limitation of a 32-bit integer return value.
      Parameters:
      filePath - the filePath argument (not null)
      Returns:
      the result (never null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • fileType

      public int fileType​(String path)
      Examines path and classifies the filesystem entry.

      -1 Unable to determine because of permissions or another error.

      0 Does not exist.

      1 Regular file.

      2 Directory.

      3 Symbolic link.

      4 Windows shortcut.

      99 Another filesystem type.

      Future values: Additional file-type codes may be added in future versions as needed.

      Parameters:
      path - the path argument (not null)
      Returns:
      the result (see ChilkatObject.getLastMethodSuccess() where the description mentions failure)
    • fileWriteBd

      public void fileWriteBd​(BinData binData, int offset, int numBytes)
      Writes bytes from binData to the currently open file. offset selects the starting byte within the BinData; numBytes selects how many bytes to write. Set both to 0 to write the entire BinData, or set numBytes to 0 to write all remaining bytes beginning at offset.
      Parameters:
      binData - the binData argument (not null)
      offset - the offset argument
      numBytes - the numBytes argument
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • genBlockId

      public String genBlockId​(int index, int length, String encoding)
      Generates a fixed-width decimal block identifier from index, padded to length characters, and then encodes those bytes using encoding (for example base64, hex, or ascii). This utility was originally added for block-oriented uploads such as Azure Blob block uploads.

      Ordering: Fixed-width decimal identifiers preserve numeric ordering when identifiers are compared lexically, provided the chosen width is large enough for all indexes.

      Parameters:
      index - the index argument
      length - the length argument
      encoding - the encoding argument (not null)
      Returns:
      the result (never null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • getDirectoryName

      public String getDirectoryName​(String path)
      Returns the directory portion of path according to Chilkat path-parsing rules.
      GetDirectoryName('C:\MyDir\MySubDir\myfile.ext')  ->  'C:\MyDir\MySubDir\'
       GetDirectoryName('C:\MyDir\MySubDir')             ->  'C:\MyDir\'
       GetDirectoryName('C:\')                             ->  'C:\'
      Parameters:
      path - the path argument (not null)
      Returns:
      the result (never null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • getExtension

      public String getExtension​(String path)
      Returns the filename extension portion of path, including the leading period. A period appearing only in a directory name is not treated as the file extension.
      GetExtension('C:\mydir.old\myfile.ext')  ->  '.ext'
       GetExtension('C:\mydir.old\')            ->  ''
      Parameters:
      path - the path argument (not null)
      Returns:
      the result (never null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • getFileName

      public String getFileName​(String path)
      Returns the final filename component of path, including its extension. If the path ends with a directory separator, the returned filename is empty.
      GetFileName('C:\mydir\myfile.ext')  ->  'myfile.ext'
       GetFileName('C:\mydir\')            ->  ''
      Parameters:
      path - the path argument (not null)
      Returns:
      the result (never null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • getFileNameWithoutExtension

      public String getFileNameWithoutExtension​(String path)
      Returns the final filename component of path with its extension removed. If path ends with a directory separator, the returned value is empty.
      GetFileNameWithoutExtension('C:\mydir\myfile.ext')  ->  'myfile'
       GetFileNameWithoutExtension('C:\mydir\')            ->  ''
      Parameters:
      path - the path argument (not null)
      Returns:
      the result (never null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • getFileTimeStr

      public String getFileTimeStr​(String path, int which)
      Returns one file timestamp as an ISO 8601 UTC string in the form YYYY-MM-DDTHH:MM:SSZ. The which argument selects 0 = last-modified, 1 = last-access, or 2 = creation.

      Portability: Creation/birth time is not available on every filesystem. The documented Chilkat behavior on Linux is to return the last-modified time when creation time is unavailable.

      Parameters:
      path - the path argument (not null)
      which - the which argument
      Returns:
      the result (never null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • getNumBlocks

      public int getNumBlocks​(int blockSize)
      Returns how many blockSize-byte blocks are required to cover the currently open file. A partial final block counts as one block. Returns 0 for an empty file and -1 if no file is open.

      Calculation: Conceptually this is ceil(fileSize / blockSize) for a non-empty file.

      Parameters:
      blockSize - the blockSize argument
      Returns:
      the result (see ChilkatObject.getLastMethodSuccess() where the description mentions failure)
    • getTempFilename

      public String getTempFilename​(String dirPath, String prefix)
      Generates a temporary pathname in dirPath using prefix and a random alphanumeric suffix, in the general form prefix_xxxx.TMP. The returned pathname is guaranteed not to already exist at the time it is generated.
      Parameters:
      dirPath - the dirPath argument (not null)
      prefix - the prefix argument (not null)
      Returns:
      the result (never null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • openForAppend

      public void openForAppend​(String filePath)
      Opens filePath for writing at end-of-file. The file is created if it does not exist. Existing content is preserved, and the initial file position is at the end.

      Open failures: If the open/create operation fails, inspect FileOpenError and FileOpenErrorMsg. On Windows, LockFileOnOpen can request exclusive access for this method.

      Parameters:
      filePath - the filePath argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • openForRead

      public void openForRead​(String filePath)
      Opens an existing filePath for reading. The file may contain text or binary data and must already exist.

      Open failures: If the open/create operation fails, inspect FileOpenError and FileOpenErrorMsg. On Windows, LockFileOnOpen can request exclusive access for this method.

      Parameters:
      filePath - the filePath argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • openForReadWrite

      public void openForReadWrite​(String filePath)
      Opens filePath for both reading and writing. The file is created if necessary. Existing content is preserved, and the initial file position is at the beginning.

      Open failures: If the open/create operation fails, inspect FileOpenError and FileOpenErrorMsg. On Windows, LockFileOnOpen can request exclusive access for this method.

      Parameters:
      filePath - the filePath argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • openForWrite

      public void openForWrite​(String filePath)
      Opens filePath for writing. The file is created if necessary; if it already exists, it is truncated to zero length when opened.

      Open failures: If the open/create operation fails, inspect FileOpenError and FileOpenErrorMsg. On Windows, LockFileOnOpen can request exclusive access for this method.

      Parameters:
      filePath - the filePath argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • readBinaryToEncoded

      public String readBinaryToEncoded​(String filePath, String encoding)
      Reads the entire file at filePath as binary data and returns an encoded textual representation. Supported encoding names documented for this method include base64, hex, qp, and url.

      Encoding is not encryption: These encodings transform bytes into text; they do not provide confidentiality.

      Parameters:
      filePath - the filePath argument (not null)
      encoding - the encoding argument (not null)
      Returns:
      the result (never null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • readBlockBd

      public void readBlockBd​(int blockIndex, int blockSize, BinData bd)
      Reads the zero-based block blockIndex from the currently open file, using blockSize bytes per block, and appends the bytes to bd. A partial final block is appended at its actual length.

      Destination behavior: Existing contents of bd are preserved; the block bytes are appended.

      Parameters:
      blockIndex - the blockIndex argument
      blockSize - the blockSize argument
      bd - the bd argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • readEntireTextFile

      public String readEntireTextFile​(String filePath, String charset)
      Reads the entire file at filePath, decodes its bytes using charset, and returns the resulting text.

      Charset matters: The charset controls byte-to-character conversion. Use the encoding that actually represents the file; incorrect charset selection can produce incorrect text or conversion failure.

      Parameters:
      filePath - the filePath argument (not null)
      charset - the charset argument (not null)
      Returns:
      the result (never null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • readNextFragment

      public int readNextFragment​(boolean startAtBeginning, String beginMarker, String endMarker, String charset, StringBuilder sb)
      Scans the currently open file for the next text fragment beginning with beginMarker and ending with endMarker. The matched fragment, including both markers, is decoded using charset and appended to sb. If startAtBeginning is true, scanning restarts at the beginning of the file; otherwise it continues after the previously matched fragment.

      1 A fragment was found and appended.

      0 No matching fragment was found.

      -1 An error occurred while reading.

      Parameters:
      startAtBeginning - the startAtBeginning argument
      beginMarker - the beginMarker argument (not null)
      endMarker - the endMarker argument (not null)
      charset - the charset argument (not null)
      sb - the sb argument (not null)
      Returns:
      the result (see ChilkatObject.getLastMethodSuccess() where the description mentions failure)
    • reassembleFile

      public void reassembleFile​(String partsDirPath, String partPrefix, String partExtension, String reassembledFilename)
      Reassembles a file previously divided by SplitFile. Parts are read from partsDirPath using the supplied partPrefix and partExtension, and the combined bytes are written to reassembledFilename.

      Byte-for-byte reconstruction: Reassembly is a binary operation; no text decoding or newline conversion is performed.

      Parameters:
      partsDirPath - the partsDirPath argument (not null)
      partPrefix - the partPrefix argument (not null)
      partExtension - the partExtension argument (not null)
      reassembledFilename - the reassembledFilename argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • replaceStrings

      public int replaceStrings​(String filePath, String charset, String existingString, String replacementString)
      Reads the file at filePath as text using charset, replaces occurrences of existingString with replacementString, writes the updated text back to the file, and returns the number of replacements made.

      Text operation: This is character-based replacement after decoding the file. It is not suitable for arbitrary binary files.

      Parameters:
      filePath - the filePath argument (not null)
      charset - the charset argument (not null)
      existingString - the existingString argument (not null)
      replacementString - the replacementString argument (not null)
      Returns:
      the result (see ChilkatObject.getLastMethodSuccess() where the description mentions failure)
    • setCurrentDir

      public void setCurrentDir​(String dirPath)
      Changes the current working directory of the calling process to dirPath.

      Process-wide effect: The current directory is normally process-wide, so changing it can affect relative paths used by other code or threads. Absolute paths avoid that dependency.

      Parameters:
      dirPath - the dirPath argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • setFileTimes

      public void setFileTimes​(String filePath, DateTime createTime, DateTime lastAccessTime, DateTime lastModTime)
      Sets the creation, last-access, and last-modified timestamps for filePath from the supplied CkDateTime objects. On filesystems that do not support a creation/birth time, createTime is ignored.

      Filesystem differences: Timestamp availability and precision are filesystem- and operating-system-dependent.

      Parameters:
      filePath - the filePath argument (not null)
      createTime - the createTime argument (not null)
      lastAccessTime - the lastAccessTime argument (not null)
      lastModTime - the lastModTime argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • setLastModified

      public void setLastModified​(String filePath, DateTime lastModified)
      Sets the last-modified timestamp of filePath from lastModified. The precision actually stored depends on the underlying filesystem.
      Parameters:
      filePath - the filePath argument (not null)
      lastModified - the lastModified argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • splitFile

      public void splitFile​(String fileToSplit, String partPrefix, String partExtension, int partSize, String destDir)
      Splits fileToSplit into sequential binary parts of up to partSize bytes and writes them to destDir using partPrefix and partExtension. Use ReassembleFile to reconstruct the original file.
      Parameters:
      fileToSplit - the fileToSplit argument (not null)
      partPrefix - the partPrefix argument (not null)
      partExtension - the partExtension argument (not null)
      partSize - the partSize argument
      destDir - the destDir argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • symlinkCreate

      public void symlinkCreate​(String targetPath, String linkPath)
      Creates a symbolic link at linkPath that refers to targetPath.

      Windows note: A Windows symbolic link is not the same as a Windows shortcut. Windows may require elevated privileges or an operating-system configuration such as Developer Mode that permits unprivileged symbolic-link creation, depending on system policy and how the application is launched.

      Parameters:
      targetPath - the targetPath argument (not null)
      linkPath - the linkPath argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • symlinkTarget

      public String symlinkTarget​(String linkPath)
      Returns the resolved target pathname for the symbolic link at linkPath. On Windows, this method also understands Windows shortcut (.lnk) files and returns the absolute target path.

      Link vs. target: A symbolic link is a filesystem object that refers to another path. A Windows shortcut is a separate shell-file format; Chilkat supports both here even though they are different mechanisms.

      Parameters:
      linkPath - the linkPath argument (not null)
      Returns:
      the result (never null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • treeDelete

      public void treeDelete​(String path)
      Recursively deletes the directory tree rooted at path, including contained files and subdirectories.

      Destructive operation: This operation is recursive and destructive. Ensure path identifies the intended tree before calling it.

      Parameters:
      path - the path argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • truncate

      public void truncate()
      Truncates the currently open file at the current file position. Bytes at and after that position are removed, making the current position the new end-of-file.

      Use with FileSeek: A common pattern is to seek to the desired new length and then call Truncate.

      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • writeEntireTextFile

      public void writeEntireTextFile​(String filePath, String textData, String charset, boolean includedPreamble)
      Creates or opens filePath, encodes textData using charset, writes the resulting bytes, and closes the file. Existing file content is replaced. If includePreamble is true, an appropriate preamble/BOM is included for encodings such as UTF-8 or UTF-16.

      BOM terminology: A BOM is part of the byte representation of the text file; it is not part of the application string itself.

      Parameters:
      filePath - the filePath argument (not null)
      textData - the textData argument (not null)
      charset - the charset argument (not null)
      includedPreamble - the includedPreamble argument
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why