Class FileAccess
- All Implemented Interfaces:
AutoCloseable
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 -
Method Summary
Modifier and TypeMethodDescriptionvoidappendAnsi(String text)Appendstextto the currently open file after converting the string to the legacy ANSI character encoding used by Chilkat for the platform.voidAppends all bytes contained inbdto the currently open file without text conversion.voidappendSb(StringBuilder sb, String charset)Appends the text contained insbto the currently open file using the character encoding specified bycharset.voidappendText(String str, String charset)Appendsstrto the currently open file after encoding the text with the character set named bycharset, such asutf-8oriso-8859-1.voidAppends the UTF-16 little-endian byte-order mark to the currently open file.voidAppends the UTF-8 byte-order mark to the currently open file.voiddirAutoCreate(String filePath)Ensures that the directory portion offilePathexists.voidCreates the directory specified bydirPath.voidDeletes the directory specified bydirPath.voiddirEnsureExists(String dirPath)Ensures that the complete directory pathdirPathexists, creating missing directories along the path as needed.booleanReturnstrueifdirPathexists as a directory; otherwise returnsfalse.voidCloses the currently open file and releases its operating-system file handle.booleanfileContentsEqual(String filePath1, String filePath2)ComparesfilePath1andfilePath2byte-for-byte and returnstrueonly when their contents are identical.voidCopiesexistingFilepathtonewFilepath.voidfileDelete(String filePath)Deletes the file specified byfilePath.booleanfileExists(String filePath)ReturnstrueiffilePathexists; otherwise returnsfalse.intfileExists3(String path)Checks whetherpathexists and returns a three-state result:1if it exists,0if it does not exist, and-1if Chilkat could not determine the result because of permissions or another filesystem error.voidfileOpen(String filePath, long accessMode, long shareMode, long createDisposition, long attributes)Windows-specific low-level open. OpensfilePathusing arguments modeled after the Win32CreateFileAPI.voidfileReadBd(int maxNumBytes, BinData binData)Reads up tomaxNumBytesbytes from the current file position and appends the bytes tobinData.voidfileRename(String existingFilepath, String newFilepath)Renames or movesexistingFilepathtonewFilepathusing the local filesystem.voidfileSeek(int offset, int origin)Moves the current file position byoffsetbytes relative toorigin.intReturns the file size in bytes as a signed 32-bit integer.longfileSize64(String filePath)Returns the size offilePathin bytes as a signed 64-bit integer.fileSizeStr(String filePath)Returns the size offilePathin bytes as a decimal string.intExaminespathand classifies the filesystem entry.voidfileWriteBd(BinData binData, int offset, int numBytes)Writes bytes frombinDatato the currently open file.genBlockId(int index, int length, String encoding)Generates a fixed-width decimal block identifier fromindex, padded tolengthcharacters, and then encodes those bytes usingencoding(for examplebase64,hex, orascii).Returns the current working directory of the calling process.getDirectoryName(String path)Returns the directory portion ofpathaccording to Chilkat path-parsing rules.booleanReturnstruewhen the currently open file is positioned at end-of-file; otherwise returnsfalse.getExtension(String path)Returns the filename extension portion ofpath, including the leading period.getFileName(String path)Returns the final filename component ofpath, including its extension.Returns the final filename component ofpathwith its extension removed.intProvides the detailed open-error code from the most recent call toFileOpen,OpenForRead,OpenForWrite,OpenForReadWrite, orOpenForAppend.Returns the human-readable message corresponding toFileOpenErrorfor the most recent file-open attempt.getFileTimeStr(String path, int which)Returns one file timestamp as an ISO 8601 UTC string in the formYYYY-MM-DDTHH:MM:SSZ.booleanWindows only. Iftrue,OpenForAppend,OpenForRead,OpenForReadWrite, andOpenForWriterequest exclusive access to the file.intgetNumBlocks(int blockSize)Returns how manyblockSize-byte blocks are required to cover the currently open file.getTempFilename(String dirPath, String prefix)Generates a temporary pathname indirPathusingprefixand a random alphanumeric suffix, in the general formprefix_xxxx.TMP.voidopenForAppend(String filePath)OpensfilePathfor writing at end-of-file.voidopenForRead(String filePath)Opens an existingfilePathfor reading.voidopenForReadWrite(String filePath)OpensfilePathfor both reading and writing.voidopenForWrite(String filePath)OpensfilePathfor writing.readBinaryToEncoded(String filePath, String encoding)Reads the entire file atfilePathas binary data and returns an encoded textual representation.voidreadBlockBd(int blockIndex, int blockSize, BinData bd)Reads the zero-based blockblockIndexfrom the currently open file, usingblockSizebytes per block, and appends the bytes tobd.readEntireTextFile(String filePath, String charset)Reads the entire file atfilePath, decodes its bytes usingcharset, and returns the resulting text.intreadNextFragment(boolean startAtBeginning, String beginMarker, String endMarker, String charset, StringBuilder sb)Scans the currently open file for the next text fragment beginning withbeginMarkerand ending withendMarker.voidreassembleFile(String partsDirPath, String partPrefix, String partExtension, String reassembledFilename)Reassembles a file previously divided bySplitFile.intreplaceStrings(String filePath, String charset, String existingString, String replacementString)Reads the file atfilePathas text usingcharset, replaces occurrences ofexistingStringwithreplacementString, writes the updated text back to the file, and returns the number of replacements made.voidsetCurrentDir(String dirPath)Changes the current working directory of the calling process todirPath.voidsetFileTimes(String filePath, DateTime createTime, DateTime lastAccessTime, DateTime lastModTime)Sets the creation, last-access, and last-modified timestamps forfilePathfrom the suppliedCkDateTimeobjects.voidsetLastModified(String filePath, DateTime lastModified)Sets the last-modified timestamp offilePathfromlastModified.voidsetLockFileOnOpen(boolean value)Sets theLockFileOnOpenproperty; seegetLockFileOnOpen().voidsplitFile(String fileToSplit, String partPrefix, String partExtension, int partSize, String destDir)SplitsfileToSplitinto sequential binary parts of up topartSizebytes and writes them todestDirusingpartPrefixandpartExtension.voidsymlinkCreate(String targetPath, String linkPath)Creates a symbolic link atlinkPaththat refers totargetPath.symlinkTarget(String linkPath)Returns the resolved target pathname for the symbolic link atlinkPath.voidtreeDelete(String path)Recursively deletes the directory tree rooted atpath, including contained files and subdirectories.voidtruncate()Truncates the currently open file at the current file position.voidwriteEntireTextFile(String filePath, String textData, String charset, boolean includedPreamble)Creates or opensfilePath, encodestextDatausingcharset, writes the resulting bytes, and closes the file.Methods inherited from class com.chilkatsoft.chilkat2.ChilkatObject
close, getDebugLogFilePath, getLastErrorHtml, getLastErrorText, getLastErrorXml, getLastMethodSuccess, getVerboseLogging, getVersion, isClosed, setDebugLogFilePath, setLastMethodSuccess, setVerboseLogging, toString
-
Constructor Details
-
FileAccess
public FileAccess()Creates a newFileAccessobject.
-
-
Method Details
-
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
FileAccessobject. Changing it can therefore affect relative-path behavior elsewhere in the application.- Returns:
- the value of the
CurrentDirproperty (read-only)
-
getEndOfFile
public boolean getEndOfFile()Returnstruewhen the currently open file is positioned at end-of-file; otherwise returnsfalse.Open-file state: This property applies to the file opened by
OpenForRead,OpenForWrite,OpenForReadWrite,OpenForAppend, orFileOpen.- Returns:
- the value of the
EndOfFileproperty (read-only)
-
getFileOpenError
public int getFileOpenError()Provides the detailed open-error code from the most recent call toFileOpen,OpenForRead,OpenForWrite,OpenForReadWrite, orOpenForAppend.Code Meaning
0Success; no open error.1Access denied.2File not found.3General, non-specific open error.4File already exists.5The path refers to a directory and the requested access involves writing.6Too many symbolic links were encountered while resolving the path.7The process already has the maximum number of files open.8The pathname is too long.9The system-wide limit on open files has been reached.10The pathname refers to a device special file for which no corresponding device exists.11Insufficient kernel memory was available.12A file was to be created, but the containing device has no space available.13A pathname component expected to be a directory is not a directory.14The regular file is too large to be opened because of an operating-system limitation.15The path is on a read-only filesystem and write access was requested.Use with FileOpenErrorMsg:
FileOpenErroris useful for programmatic handling;FileOpenErrorMsgprovides the corresponding human-readable message.- Returns:
- the value of the
FileOpenErrorproperty (read-only)
-
getFileOpenErrorMsg
Returns the human-readable message corresponding toFileOpenErrorfor the most recent file-open attempt.- Returns:
- the value of the
FileOpenErrorMsgproperty (read-only)
-
getLockFileOnOpen
public boolean getLockFileOnOpen()Windows only. Iftrue,OpenForAppend,OpenForRead,OpenForReadWrite, andOpenForWriterequest exclusive access to the file. Other processes are prevented from opening the file untilFileClosereleases the handle. The default isfalse.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
LockFileOnOpenproperty
-
setLockFileOnOpen
public void setLockFileOnOpen(boolean value)Sets theLockFileOnOpenproperty; seegetLockFileOnOpen().- Parameters:
value- the new value
-
appendAnsi
Appendstextto the currently open file after converting the string to the legacy ANSI character encoding used by Chilkat for the platform.Character encoding: Use
AppendTextorAppendSbwhen an explicit encoding such asutf-8is preferred.- Parameters:
text- thetextargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
appendBd
Appends all bytes contained inbdto the currently open file without text conversion.- Parameters:
bd- thebdargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
appendSb
Appends the text contained insbto the currently open file using the character encoding specified bycharset.- Parameters:
sb- thesbargument (notnull)charset- thecharsetargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
appendText
Appendsstrto the currently open file after encoding the text with the character set named bycharset, such asutf-8oriso-8859-1.- Parameters:
str- thestrargument (notnull)charset- thecharsetargument (notnull)- 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 areFF 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 areEF 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
Ensures that the directory portion offilePathexists. 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
DirAutoCreatewhen you have a file path. UseDirEnsureExistswhen the argument itself is a directory path.- Parameters:
filePath- thefilePathargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
dirCreate
Creates the directory specified bydirPath. Parent directories must already exist; useDirEnsureExistswhen missing parent directories should also be created.- Parameters:
dirPath- thedirPathargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
dirDelete
Deletes the directory specified bydirPath. The directory must be empty; useTreeDeleteto recursively delete a directory and its contents.- Parameters:
dirPath- thedirPathargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
dirEnsureExists
Ensures that the complete directory pathdirPathexists, creating missing directories along the path as needed.- Parameters:
dirPath- thedirPathargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
dirExists
ReturnstrueifdirPathexists as a directory; otherwise returnsfalse.- Parameters:
dirPath- thedirPathargument (notnull)- 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 throughLockFileOnOpenis released at this time. -
fileContentsEqual
ComparesfilePath1andfilePath2byte-for-byte and returnstrueonly 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- thefilePath1argument (notnull)filePath2- thefilePath2argument (notnull)- Returns:
- the result; this method never throws
ChilkatException
-
fileCopy
CopiesexistingFilepathtonewFilepath. IffailIfExistsistrueand the destination already exists, the copy fails instead of overwriting it.- Parameters:
existingFilepath- theexistingFilepathargument (notnull)newFilepath- thenewFilepathargument (notnull)failIfExists- thefailIfExistsargument- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
fileDelete
Deletes the file specified byfilePath.- Parameters:
filePath- thefilePathargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
fileExists
ReturnstrueiffilePathexists; otherwise returnsfalse. UseFileExists3when the application must distinguish "does not exist" from "could not determine because of an error."- Parameters:
filePath- thefilePathargument (notnull)- Returns:
- the result; this method never throws
ChilkatException
-
fileExists3
Checks whetherpathexists and returns a three-state result:1if it exists,0if it does not exist, and-1if Chilkat could not determine the result because of permissions or another filesystem error.- Parameters:
path- thepathargument (notnull)- 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. OpensfilePathusing arguments modeled after the Win32CreateFileAPI. For portable code, preferOpenForRead,OpenForWrite,OpenForReadWrite, orOpenForAppend.Category Common values
Access
GENERIC_READ = 0x80000000,GENERIC_WRITE = 0x40000000Sharing
FILE_SHARE_READ = 0x1,FILE_SHARE_WRITE = 0x2Disposition
CREATE_NEW=1,CREATE_ALWAYS=2,OPEN_EXISTING=3,OPEN_ALWAYS=4,TRUNCATE_EXISTING=5Open failures: When this method fails, inspect
FileOpenErrorandFileOpenErrorMsgfor the reason.- Parameters:
filePath- thefilePathargument (notnull)accessMode- theaccessModeargument (0 .. 4294967295)shareMode- theshareModeargument (0 .. 4294967295)createDisposition- thecreateDispositionargument (0 .. 4294967295)attributes- theattributesargument (0 .. 4294967295)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
fileReadBd
Reads up tomaxNumBytesbytes from the current file position and appends the bytes tobinData. The file position advances by the number of bytes read.Destination behavior: Existing bytes already present in
binDataare preserved; newly read bytes are appended.- Parameters:
maxNumBytes- themaxNumBytesargumentbinData- thebinDataargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
fileRename
Renames or movesexistingFilepathtonewFilepathusing the local filesystem.- Parameters:
existingFilepath- theexistingFilepathargument (notnull)newFilepath- thenewFilepathargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
fileSeek
public void fileSeek(int offset, int origin)Moves the current file position byoffsetbytes relative toorigin.0Offset from the beginning of the file.1Offset from the current file position.2Offset 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- theoffsetargumentorigin- theoriginargument- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
fileSize
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, useFileSizeStr, which fails instead of returning a size, or check first withFileExists3.Large files: A signed 32-bit result cannot represent files larger than approximately 2 GB. UseFileSize64orFileSizeStrfor large files.- Parameters:
filePath- thefilePathargument (notnull)- Returns:
- the result (see
ChilkatObject.getLastMethodSuccess()where the description mentions failure)
-
fileSize64
Returns the size offilePathin 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, useFileSizeStr, which fails instead of returning a size, or check first withFileExists3.- Parameters:
filePath- thefilePathargument (notnull)- Returns:
- the result (see
ChilkatObject.getLastMethodSuccess()where the description mentions failure)
-
fileSizeStr
Returns the size offilePathin bytes as a decimal string. This avoids the range limitation of a 32-bit integer return value.- Parameters:
filePath- thefilePathargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
fileType
Examinespathand classifies the filesystem entry.-1Unable to determine because of permissions or another error.0Does not exist.1Regular file.2Directory.3Symbolic link.4Windows shortcut.99Another filesystem type.Future values: Additional file-type codes may be added in future versions as needed.
- Parameters:
path- thepathargument (notnull)- Returns:
- the result (see
ChilkatObject.getLastMethodSuccess()where the description mentions failure)
-
fileWriteBd
Writes bytes frombinDatato the currently open file.offsetselects the starting byte within theBinData;numBytesselects how many bytes to write. Set both to0to write the entireBinData, or setnumBytesto0to write all remaining bytes beginning atoffset.- Parameters:
binData- thebinDataargument (notnull)offset- theoffsetargumentnumBytes- thenumBytesargument- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
genBlockId
Generates a fixed-width decimal block identifier fromindex, padded tolengthcharacters, and then encodes those bytes usingencoding(for examplebase64,hex, orascii). 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- theindexargumentlength- thelengthargumentencoding- theencodingargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
getDirectoryName
Returns the directory portion ofpathaccording 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- thepathargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
getExtension
Returns the filename extension portion ofpath, 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- thepathargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
getFileName
Returns the final filename component ofpath, 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- thepathargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
getFileNameWithoutExtension
Returns the final filename component ofpathwith its extension removed. Ifpathends with a directory separator, the returned value is empty.GetFileNameWithoutExtension('C:\mydir\myfile.ext') -> 'myfile' GetFileNameWithoutExtension('C:\mydir\') -> ''- Parameters:
path- thepathargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
getFileTimeStr
Returns one file timestamp as an ISO 8601 UTC string in the formYYYY-MM-DDTHH:MM:SSZ. Thewhichargument selects0= last-modified,1= last-access, or2= 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- thepathargument (notnull)which- thewhichargument- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
getNumBlocks
public int getNumBlocks(int blockSize)Returns how manyblockSize-byte blocks are required to cover the currently open file. A partial final block counts as one block. Returns0for an empty file and-1if no file is open.Calculation: Conceptually this is
ceil(fileSize / blockSize)for a non-empty file.- Parameters:
blockSize- theblockSizeargument- Returns:
- the result (see
ChilkatObject.getLastMethodSuccess()where the description mentions failure)
-
getTempFilename
Generates a temporary pathname indirPathusingprefixand a random alphanumeric suffix, in the general formprefix_xxxx.TMP. The returned pathname is guaranteed not to already exist at the time it is generated.- Parameters:
dirPath- thedirPathargument (notnull)prefix- theprefixargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
openForAppend
OpensfilePathfor 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
FileOpenErrorandFileOpenErrorMsg. On Windows,LockFileOnOpencan request exclusive access for this method.- Parameters:
filePath- thefilePathargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
openForRead
Opens an existingfilePathfor reading. The file may contain text or binary data and must already exist.Open failures: If the open/create operation fails, inspect
FileOpenErrorandFileOpenErrorMsg. On Windows,LockFileOnOpencan request exclusive access for this method.- Parameters:
filePath- thefilePathargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
openForReadWrite
OpensfilePathfor 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
FileOpenErrorandFileOpenErrorMsg. On Windows,LockFileOnOpencan request exclusive access for this method.- Parameters:
filePath- thefilePathargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
openForWrite
OpensfilePathfor 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
FileOpenErrorandFileOpenErrorMsg. On Windows,LockFileOnOpencan request exclusive access for this method.- Parameters:
filePath- thefilePathargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
readBinaryToEncoded
Reads the entire file atfilePathas binary data and returns an encoded textual representation. Supported encoding names documented for this method includebase64,hex,qp, andurl.Encoding is not encryption: These encodings transform bytes into text; they do not provide confidentiality.
- Parameters:
filePath- thefilePathargument (notnull)encoding- theencodingargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
readBlockBd
Reads the zero-based blockblockIndexfrom the currently open file, usingblockSizebytes per block, and appends the bytes tobd. A partial final block is appended at its actual length.Destination behavior: Existing contents of
bdare preserved; the block bytes are appended.- Parameters:
blockIndex- theblockIndexargumentblockSize- theblockSizeargumentbd- thebdargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
readEntireTextFile
Reads the entire file atfilePath, decodes its bytes usingcharset, 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- thefilePathargument (notnull)charset- thecharsetargument (notnull)- 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 withbeginMarkerand ending withendMarker. The matched fragment, including both markers, is decoded usingcharsetand appended tosb. IfstartAtBeginningistrue, scanning restarts at the beginning of the file; otherwise it continues after the previously matched fragment.1A fragment was found and appended.0No matching fragment was found.-1An error occurred while reading.- Parameters:
startAtBeginning- thestartAtBeginningargumentbeginMarker- thebeginMarkerargument (notnull)endMarker- theendMarkerargument (notnull)charset- thecharsetargument (notnull)sb- thesbargument (notnull)- 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 bySplitFile. Parts are read frompartsDirPathusing the suppliedpartPrefixandpartExtension, and the combined bytes are written toreassembledFilename.Byte-for-byte reconstruction: Reassembly is a binary operation; no text decoding or newline conversion is performed.
- Parameters:
partsDirPath- thepartsDirPathargument (notnull)partPrefix- thepartPrefixargument (notnull)partExtension- thepartExtensionargument (notnull)reassembledFilename- thereassembledFilenameargument (notnull)- 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 atfilePathas text usingcharset, replaces occurrences ofexistingStringwithreplacementString, 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- thefilePathargument (notnull)charset- thecharsetargument (notnull)existingString- theexistingStringargument (notnull)replacementString- thereplacementStringargument (notnull)- Returns:
- the result (see
ChilkatObject.getLastMethodSuccess()where the description mentions failure)
-
setCurrentDir
Changes the current working directory of the calling process todirPath.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- thedirPathargument (notnull)- 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 forfilePathfrom the suppliedCkDateTimeobjects. On filesystems that do not support a creation/birth time,createTimeis ignored.Filesystem differences: Timestamp availability and precision are filesystem- and operating-system-dependent.
- Parameters:
filePath- thefilePathargument (notnull)createTime- thecreateTimeargument (notnull)lastAccessTime- thelastAccessTimeargument (notnull)lastModTime- thelastModTimeargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setLastModified
Sets the last-modified timestamp offilePathfromlastModified. The precision actually stored depends on the underlying filesystem.- Parameters:
filePath- thefilePathargument (notnull)lastModified- thelastModifiedargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
splitFile
public void splitFile(String fileToSplit, String partPrefix, String partExtension, int partSize, String destDir)SplitsfileToSplitinto sequential binary parts of up topartSizebytes and writes them todestDirusingpartPrefixandpartExtension. UseReassembleFileto reconstruct the original file.- Parameters:
fileToSplit- thefileToSplitargument (notnull)partPrefix- thepartPrefixargument (notnull)partExtension- thepartExtensionargument (notnull)partSize- thepartSizeargumentdestDir- thedestDirargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
symlinkCreate
Creates a symbolic link atlinkPaththat refers totargetPath.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- thetargetPathargument (notnull)linkPath- thelinkPathargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
symlinkTarget
Returns the resolved target pathname for the symbolic link atlinkPath. 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- thelinkPathargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
treeDelete
Recursively deletes the directory tree rooted atpath, including contained files and subdirectories.Destructive operation: This operation is recursive and destructive. Ensure
pathidentifies the intended tree before calling it.- Parameters:
path- thepathargument (notnull)- 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 opensfilePath, encodestextDatausingcharset, writes the resulting bytes, and closes the file. Existing file content is replaced. IfincludePreambleistrue, 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- thefilePathargument (notnull)textData- thetextDataargument (notnull)charset- thecharsetargument (notnull)includedPreamble- theincludedPreambleargument- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-