AnyLogic
Expand
Font size
All Implemented Interfaces:
com.anylogic.engine.internal.Child, Serializable

public class TextFile
extends Object
implements Serializable, com.anylogic.engine.internal.Child
Text File access utility

Write mode description:
This object has following methods for writing to the file:

Read mode description:
This object reads text file line by line. Class defines method getLineNumber() for getting the current line number.
By default, line numbering begins at 0. This number increments at every line terminator as the data is read.

A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a line feed.

In the reading mode, on each reading method call (e.g. readDouble()), TextFile advances reading position to the next value that can be read. I.e. it reads requested data and skips all trailing separatorsForReading that were specified in the constructor.

Common information:
Initially, TextFile is in 'not open' state: any further accessor-method call (e.g. print(double)) will open file, i.e.

  • next reading (if in READ mode) will start reading file from its beginning
  • next writing (if in WRITE mode) will start rewriting or appending (depends on mode)

TextFile has skipping methods skipChars(long) and skipTokens(int) which may be used to skip (preliminarily known) number of characters/tokens in the file

Author:
AnyLogic North America, LLC https://anylogic.com
See Also:
Serialized Form

Nested Class Summary

Modifier and TypeClassDescription
static enum TextFile.Mode
File operations mode constants

Field Summary

Modifier and TypeFieldDescription
static final TextFile.ModeREAD
'read' mode
static final TextFile.ModeWRITE
'write' mode
static final TextFile.ModeWRITE_APPEND
'write/append' mode

Constructor Summary

ConstructorDescription
TextFile(Presentable owner, String packagePrefix, TextFile.Mode mode, String fileName, String charsetName, char[] separatorsForReading)
Creates new TextFile object based on given name of file
TextFile(Presentable owner, String packagePrefix, URL url, String charsetName, char[] separatorsForReading)
Creates new TextFile object in READ mode, based on given URL

Method Summary

Modifier and TypeMethodDescription
booleancanReadMore()
Returns true if there is available content in the file at the reading position.
This method opens file for reading if it is not open.
This method is only available in READ mode
voidclose()
Closes the read or write stream of this TextFile and releases any system resources associated with it.
intgetLineNumber()
Get the current line number.
This method is only available in READ mode
StringgetLocation()
Returns the location (path) of the file.
Returns null if the file location hasn't been set.
voidprint(boolean b)
Prints a boolean value.
voidprint(char c)
Prints a character.
voidprint(char[] s)
Prints an array of characters.
voidprint(double d)
Prints a double-precision floating-point number.
voidprint(float f)
Prints a floating-point number.
voidprint(int i)
Prints an integer.
voidprint(long l)
Prints a long integer.
voidprint(Object obj)
Prints an object.
voidprint(String s)
Prints a string.
voidprintf(String format, Object... args)
A convenient method to write a formatted string to the text file using the specified format string and arguments.
voidprintf(Locale l, String format, Object... args)
A convenient method to write a formatted string to the text file using the specified format string and arguments.
voidprintln()
Terminates the current line by writing the line separator string.
voidprintln(boolean x)
Prints a boolean value and then terminates the line.
voidprintln(char x)
Prints a character and then terminates the line.
voidprintln(char[] x)
Prints an array of characters and then terminates the line.
voidprintln(double x)
Prints a double-precision floating-point number and then terminates the line.
voidprintln(float x)
Prints a floating-point number and then terminates the line.
voidprintln(int x)
Prints an integer and then terminates the line.
voidprintln(long x)
Prints a long integer and then terminates the line.
voidprintln(Object x)
Prints an Object and then terminates the line.
voidprintln(String x)
Prints a String and then terminates the line.
booleanreadBoolean()
Reads boolean string "true" or "false" (with or without quotation marks)
bytereadByte()
Reads and returns number as byte.
charreadChar()
Reads and returns one character.
Throws exception if there is separator in the current reading position or current text before next separator has more than one character
doublereadDouble()
Reads and returns a double value (number with floating-point and double-precision).
floatreadFloat()
Reads and returns a float value (number with floating-point).
intreadInt()
Reads and returns an int value.
Int value is a number in the range Integer.MIN_VALUE ...
StringreadLine()
Read a line of text.
longreadLong()
Reads and returns a long value.
Long value is a number in the range Long.MIN_VALUE ...
shortreadShort()
Reads and returns a short value.
Short value is a number in the range Short.MIN_VALUE ...
StringreadString()
Reads and returns a String which contains text from current reading position (which is after previously read separator), inclusive, to the next separator character position, exclusive
voidrestoreOwner(Object owner)
Deprecated.
voidsetFile(String fileName, TextFile.Mode mode)
Sets the new file to be used with this TextFile object
If specified file differs from previously used and the latter is not closed, it will be closed
For TextFile based on URL or on file among class resources, the only possible mode is READ
voidsetMode(TextFile.Mode mode)
Sets the new mode of this TextFile object
If specified mode differs from previously used and the file is not closed, it will be closed
For TextFile based on URL or on file among class resources, the only possible mode is READ
voidsetURL(URL url)
Sets the new url to be used with this TextFile object
This method switches TextFile to the READ mode
If specified url differs from previously used and the stream of latter is not closed, it will be closed
longskipChars(long n)
Skip characters (as well as separator characters).
intskipTokens(int n)
Skips tokens (texts between separators declared in the constructor)
StringtoString() 

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Details

READ

public static final TextFile.Mode READ
'read' mode

WRITE

public static final TextFile.Mode WRITE
'write' mode

WRITE_APPEND

public static final TextFile.Mode WRITE_APPEND
'write/append' mode

Constructor Details

TextFile

public TextFile(Presentable owner,
 String packagePrefix,
 TextFile.Mode mode,
 String fileName,
 String charsetName,
 char[] separatorsForReading)
Creates new TextFile object based on given name of file
Parameters:
owner - this object's owner (agent or experiment)
packagePrefix - the package name of original agent where this image is defined, formatted using '/' characters; with '/' character at the beginning and at the end
mode - possible values:
fileName -
  • absolute path to the file
  • path to file relative to current working directory
  • name of file which is among resources of owner's class (if included into the class-path and lies in the owner's package) - only READ mode
charsetName - The name of a supported charset
Available charset names can be obtained calling Charset.availableCharsets().keySet()
use null for the default system charset
separatorsForReading - an array (may be null) of characters which should be assumed as token-separators. To define line-separator, use '\n' character. It is also important whether this array includes line-separator ('\n') or not. If doesn't then e.g. readString() may return string with multiple lines

For example, read tab-separated file can be processed using separatorsForReading = new char[]{ '\n', '\t' }

TextFile

public TextFile(Presentable owner,
 String packagePrefix,
 URL url,
 String charsetName,
 char[] separatorsForReading)
Creates new TextFile object in READ mode, based on given URL
Parameters:
owner - this object's owner (agent or experiment)
packagePrefix - the package name of original agent where this image is defined, formatted using '/' characters; with '/' character at the beginning and at the end
url - the url to contents which should be read
charsetName - The name of a supported charset
Available charset names can be obtained calling Charset.availableCharsets().keySet()
use null for the default system charset
separatorsForReading - an array (may be null) of characters which should be assumed as token-separators. To define line-separator, use '\n' character. It is also important whether this array includes line-separator ('\n') or not. If doesn't then e.g. readString() may return string with multiple lines

For example, read tab-separated file can be processed using separatorsForReading = new char[]{ '\n', '\t' }

Method Details

restoreOwner

@AnyLogicInternalCodegenAPI
@Deprecated
public void restoreOwner(Object owner)
Deprecated.
This method normally should not be called by user
This method restores owner of this object
The method is used in snapshot saving/loading
Specified by:
restoreOwner in interface com.anylogic.engine.internal.Child
Parameters:
owner - owner of this object, usually Agent, Experiment or ShapeGroup

close

public void close()
Closes the read or write stream of this TextFile and releases any system resources associated with it. Returns this object to 'not open' state
Closing a previously closed TextFile has no effect.

setFile

public void setFile(String fileName,
 TextFile.Mode mode)
Sets the new file to be used with this TextFile object
If specified file differs from previously used and the latter is not closed, it will be closed
For TextFile based on URL or on file among class resources, the only possible mode is READ
Parameters:
fileName -
  • absolute path to the file
  • path to file relative to current working directory
  • name of file which is among resources of owner's class (if included into the class-path and lies in the owner's package) - only READ mode
mode - possible values:

getLocation

public String getLocation()
Returns the location (path) of the file.
Returns null if the file location hasn't been set.
Returns:
the location of the file.
See Also:

setURL

public void setURL(URL url)
Sets the new url to be used with this TextFile object
This method switches TextFile to the READ mode
If specified url differs from previously used and the stream of latter is not closed, it will be closed
Parameters:
url - the url to contents which should be read

setMode

public void setMode(TextFile.Mode mode)
Sets the new mode of this TextFile object
If specified mode differs from previously used and the file is not closed, it will be closed
For TextFile based on URL or on file among class resources, the only possible mode is READ
Parameters:
mode - possible values:

print

public void print(boolean b)
Prints a boolean value. The string produced by String.valueOf(boolean) is translated into bytes according to the chosen character encoding, and these bytes are written to the file.
Parameters:
b - The boolean to be printed

print

public void print(char c)
Prints a character. The character is translated into one or more bytes according to the chosen character encoding, and these bytes are written to the file.
Parameters:
c - The char to be printed

print

public void print(char[] s)
Prints an array of characters. The characters are converted into bytes according to the chosen character encoding, and these bytes are written to the file.
Parameters:
s - The array of chars to be printed
Throws:
NullPointerException - If s is null

print

public void print(double d)
Prints a double-precision floating-point number. The string produced by String.valueOf(double) is translated into bytes according to the chosen character encoding, and these bytes are written to the file.
Parameters:
d - The double to be printed
See Also:
Double.toString(double)

print

public void print(float f)
Prints a floating-point number. The string produced by String.valueOf(float) is translated into bytes according to the chosen character encoding, and these bytes are written to the file.
Parameters:
f - The float to be printed
See Also:
Float.toString(float)

print

public void print(int i)
Prints an integer. The string produced by String.valueOf(int) is translated into bytes according to the chosen character encoding, and these bytes are written to the file.
Parameters:
i - The int to be printed
See Also:
Integer.toString(int)

print

public void print(long l)
Prints a long integer. The string produced by String.valueOf(long) is translated into bytes according to the chosen character encoding, and these bytes are written to the file.
Parameters:
l - The long to be printed
See Also:
Long.toString(long)

print

public void print(Object obj)
Prints an object. The string produced by the String.valueOf(Object) method is translated into bytes according to the chosen character encoding, and these bytes are written to the file.
Parameters:
obj - The Object to be printed
See Also:
Object.toString()

print

public void print(String s)
Prints a string. If the argument is null then the string "null" is printed. Otherwise, the string's characters are converted into bytes according to the chosen character encoding, and these bytes are written to the file.
Parameters:
s - The String to be printed

println

public void println()
Terminates the current line by writing the line separator string. The line separator string is defined by the system property line.separator, and is not necessarily a single newline character ('\n').

println

public void println(boolean x)
Prints a boolean value and then terminates the line. This method behaves as though it invokes print(boolean) and then println().
Parameters:
x - the boolean value to be printed

println

public void println(char x)
Prints a character and then terminates the line. This method behaves as though it invokes print(char) and then println().
Parameters:
x - the char value to be printed

println

public void println(char[] x)
Prints an array of characters and then terminates the line. This method behaves as though it invokes print(char[]) and then println().
Parameters:
x - the array of char values to be printed

println

public void println(double x)
Prints a double-precision floating-point number and then terminates the line. This method behaves as though it invokes print(double) and then println().
Parameters:
x - the double value to be printed

println

public void println(float x)
Prints a floating-point number and then terminates the line. This method behaves as though it invokes print(float) and then println().
Parameters:
x - the float value to be printed

println

public void println(int x)
Prints an integer and then terminates the line. This method behaves as though it invokes print(int) and then println().
Parameters:
x - the int value to be printed

println

public void println(long x)
Prints a long integer and then terminates the line. This method behaves as though it invokes print(long) and then println().
Parameters:
x - the long value to be printed

println

public void println(Object x)
Prints an Object and then terminates the line. This method calls at first String.valueOf(x) to get the printed object's string value, then behaves as though it invokes print(String) and then println().
Parameters:
x - The Object to be printed.

println

public void println(String x)
Prints a String and then terminates the line. This method behaves as though it invokes print(String) and then println().
Parameters:
x - the String value to be printed

printf

public void printf(Locale l,
 String format,
 Object... args)
A convenient method to write a formatted string to the text file using the specified format string and arguments.
Parameters:
l - The locale to apply during formatting. If l is null then no localization is applied.
format - A format string as described in Formatter class specification.
args - Arguments referenced by the format specifiers in the format string. If there are more arguments than format specifiers, the extra arguments are ignored. The number of arguments is variable and may be zero. The maximum number of arguments is limited by the maximum dimension of a Java array as defined by the Java Virtual Machine Specification. The behavior on a null argument depends on the conversion of Formatter.
Throws:
IllegalFormatException - If a format string contains an illegal syntax, a format specifier that is incompatible with the given arguments, insufficient arguments given the format string, or other illegal conditions. For specification of all possible formatting errors, see the Details section of the Formatter class specification.
NullPointerException - If the format is null

printf

public void printf(String format,
 Object... args)
A convenient method to write a formatted string to the text file using the specified format string and arguments.
Parameters:
format - A format string as described in Formatter class specification.
args - Arguments referenced by the format specifiers in the format string. If there are more arguments than format specifiers, the extra arguments are ignored. The number of arguments is variable and may be zero. The maximum number of arguments is limited by the maximum dimension of a Java array as defined by the Java Virtual Machine Specification. The behavior on a null argument depends on the conversion of Formatter.
Throws:
IllegalFormatException - If a format string contains an illegal syntax, a format specifier that is incompatible with the given arguments, insufficient arguments given the format string, or other illegal conditions. For specification of all possible formatting errors, see the Details section of the Formatter class specification.
NullPointerException - If the format is null

getLineNumber

public int getLineNumber()
Get the current line number.
This method is only available in READ mode
Returns:
  • the current line number (1-based)
  • 0 if the file hasn't been opened yet (no read- and skip-methods haven't been called as well as canReadMore())
  • -1 if the end of the file has been reached

canReadMore

public boolean canReadMore()
Returns true if there is available content in the file at the reading position.
This method opens file for reading if it is not open.
This method is only available in READ mode
Returns:
true if there is available content in the file at the reading position, false if the end of file has been reached

readLine

public String readLine()
Read a line of text. Whenever a line terminator is read the current line number is incremented.
If the current reading position is in the middle of line (e.g. current line is "33;Car" and readInt() was called once), the rest part of line is returned (in the given example it is "Car" - if this TextFile has separator ';')
Returns:
A String containing the contents of the line (from current reading position), not including any line termination characters, or null if the end of the stream has been reached

readBoolean

public boolean readBoolean()
Reads boolean string "true" or "false" (with or without quotation marks)
Returns:
the boolean value read.

readByte

public byte readByte()
Reads and returns number as byte. Byte value is a number in the range Byte.MIN_VALUE ... Byte.MAX_VALUE, inclusive.
Returns:
the byte number value read.

readShort

public short readShort()
Reads and returns a short value.
Short value is a number in the range Short.MIN_VALUE ... Short.MAX_VALUE, inclusive
Returns:
the short value read.

readChar

public char readChar()
Reads and returns one character.
Throws exception if there is separator in the current reading position or current text before next separator has more than one character
Returns:
the char value of character read.

readInt

public int readInt()
Reads and returns an int value.
Int value is a number in the range Integer.MIN_VALUE ... Integer.MAX_VALUE, inclusive
Returns:
the int value read.

readLong

public long readLong()
Reads and returns a long value.
Long value is a number in the range Long.MIN_VALUE ... Long.MAX_VALUE, inclusive
Returns:
the long value read.

readFloat

public float readFloat()
Reads and returns a float value (number with floating-point).
Returns:
the float value read.

readDouble

public double readDouble()
Reads and returns a double value (number with floating-point and double-precision).
Returns:
the double value read.

readString

public String readString()
Reads and returns a String which contains text from current reading position (which is after previously read separator), inclusive, to the next separator character position, exclusive
Returns:
the double value read.

skipChars

public long skipChars(long n)
Skip characters (as well as separator characters).
Parameters:
n - the number of characters to skip
Returns:
the number of characters actually skipped
Throws:
IllegalArgumentException - If n is negative

skipTokens

public int skipTokens(int n)
Skips tokens (texts between separators declared in the constructor)
Parameters:
n - the number of tokens to skip
Returns:
the number of tokens actually skipped
Throws:
IllegalArgumentException - If n is negative

toString

public String toString()
Overrides:
toString in class Object