File Class Methods

In this section, we discuss the File class methods. The methods are discussed in alphabetical order.

Syntax

Close()

Description

The Close method discards any changes that haven’t been written to the external file, disassociates the file object from the external file, releases all resources connected with the file object, and causes the file object to go out of scope.

You cannot use any methods or properties on the object after it is closed. You must get another file object (using the GetFile function) and instantiate another file object after you use Close.

Parameters

None.

Returns

None.

Example

&MYFILE.Open("somefile.txt", "W", %FilePath_Relative);
&MYFILE.WriteLine("Some text.");
&MYFILE.Close();

Syntax

CreateRowset()

Description

The CreateRowset method is a file layout method. It instantiates a PeopleCode rowset object containing one unpopulated row, based on the file layout definition specified with SetFileLayout.

Note: You must specify a file layout using the SetFileLayout method before using CreateRowset, otherwise it returns NULL.

See SetFileLayout.

After the empty rowset object has been created, you can use Rowset class methods such as Select or Fill, and built-in functions such as GetLevel0 or GetRowset, to populate the rowset with data. After the rowset contains data, you can use the method WriteRowset to write the data to a file.

Don’t use CreateRowset when reading from a file. Instead, use the ReadRowset method to instantiate and populate rowsets with data from the file.

Parameters

None.

Returns

An empty rowset object.

Example

&SOMEROWSET = &MYFILE.CreateRowset();

The following rowset is created from a file object, then populated with data using the GetLevel0 function:

&FILEROWSET = &MYFILE.CreateRowset();
&FILEROWSET = GetLevel0();
&MYFILE.WriteRowset(&FILEROWSET, True);

The following rowset is created from a file object, then populated with data using Fill method:

&FILEROWSET = &MYFILE.CreateRowset();
&NUM_READ = &FILEROWSET.Fill("where MYRECORD = :1", &UVAL);

Syntax

Delete()

Description

Use the Delete method to delete an open file. You cannot delete a closed file.

Parameters

None.

Returns

None.

Example

/* Open a temporary file. Use the "N" parameter to ensure
the file is new. */

&MyFile = GetFile("temp.txt", "N");

/* verify the file was instantiated successfully */

/* do processing using the temporary file */

/* delete the temporary file */

&MyFile.Delete();

Syntax

GetBase64StringFromBinary()

Description

Use this method to read the complete contents of the binary file associated with the current File object, encode the data using Base64, and return the result as a Base64-encoded string.

Parameters

None.

Returns

A string containing the contents of the binary file encoded in Base64.

Example

Local File &F1;
Local string &base64string;

&F1 = GetFile("D:\image.jpg", "R", %FilePath_Absolute);
If &F1.IsOpen Then
   &base64string = &F1.GetBase64StringFromBinary();
   &F1.Close();
End-If;

Syntax

GetPosition()

Description

The GetPosition method returns the current read or write position in the external file. GetPosition works only with a file that was opened in Update mode. This method is designed to be used in combination with the SetPosition method to establish checkpoints for restarting during file access.

Note: Currently, the effect of the Update mode and the GetPosition and SetPosition methods is not well defined for Unicode files. Use the Update mode only on files stored with a non-Unicode character set.

Parameters

None.

Returns

A number representing the current read or write position in the file.

Note: When you use ReadRowset to read from a file in Update mode, the CurrentRecord property returns, the entire record just read. The current read/write position is at the end of the CurrentRecord, that is, just past the end of the rowset.

Example

The following example opens a file in Update mode, and saves the current position after each read operation:

&MYFILE.Open(&SOMENAME, "U");
If &MYFILE.IsOpen Then
   while &MYFILE.ReadLine(&SOMESTRING)
      &CURPOS = &MYFILE.GetPosition();
      /* Save the value of &CURPOS after each read,
         and process the contents of each &SOMESTRING */
   End-While;
End-If;
&MYFILE.Close();

Syntax

GetString([Strip_Line_Terminator])

Description

Use the GetString method to return the entire file as a single string.

Note: After this method completes successfully, the original file is deleted.

You can specify whether the resulting string is to include the line terminator characters or not by using the Strip_Line_Terminator parameter. The default value for this parameter is false, which means the resulting string includes the line terminator characters at the end of each line.

For example on a Unix system, with a line terminator of a LF, the resulting string includes not only the data for each line, but the LF character as well.

Parameters

Field or Control

Definition

Strip_Line_Terminator

Specify whether the line terminators are to be stripped or not.

Returns

A single string containing the entire contents of the file.

Example

The following example creates a file on a Windows system, then retrieves it as a single line of text.

Note: The file is destroyed on successful completion of this method.

Local File &File = GetFile("c:\temp\junk\something.txt", "W", %FilePath_Absolute)
/* write a bunch of > 2048 length lines */

Local string &piece, &input;
Local integer &I;

&piece = "123456789-";
While Len(&piece) < 2048
   &piece = &piece | &piece;
End-While;

&File.WriteString(&piece);
&File.WriteString(&piece);
&File.WriteString(&piece);
&input = &File.GetString( True);
&File.Close();
Local string &pieces = &piece | &piece | &piece;

/* Note that the result of this message should indicate &pieces is the same as &input */
MessageBox(0, "", 0, 0, "&piece = &input: Len(&pieces)=" | Len(&pieces) | " Len(&input)=" | Len(&input) | " Same? " | (&pieces = &input));

Syntax

Open(filespec, mode [, charset] [, pathtype])

Description

The Open method associates the file object with an external file for input or output.

If the File object is currently associated with a file, that file is closed first. In addition, any file opened for writing (by a call to the GetFile function or the Open method) by a PeopleCode program that runs in the Process Scheduler is automatically managed by the Report Repository.

You can use the GetFile or GetTempFile functions to access an external file, but each execution of GetFile or GetTempFile instantiates a new file object. If you plan to access only one file at a time, you need only one file object. Use GetFile or GetTempFile to instantiate a file object for the first external file you access. Then, use Open to associate the same file object with as many different external files as you want. However, if you expect to have multiple files open at the same time, you need to instantiate multiple file objects with GetFile or GetTempFile.

GetFile and Open both perform implicit commits. Therefore, the GetTempFile function has been introduced specifically to avoid these implicit database commits. GetTempFile differs from GetFile in two respects:

  • GetTempFile does not perform an implicit commit.

  • GetTempFile does not make the associated file available through the Report Repository even when the calling PeopleCode program is run through the Process Scheduler.

Therefore, GetTempFile can be a good choice when you wish to avoid implicit database commits and when you do not need to have the file managed through the Report Repository. Otherwise, GetTempFile operates exactly the same as GetFile.

Parameters

Field or Control

Definition

filespec

Specify the name, and optionally, the path, of the file you want to open.

mode

A string indicating the manner in which you want to access the file. The mode can be one of the following:

  • "R" (Read mode): opens the file for reading, starting at the beginning.

  • "W" (Write mode): opens the file for writing.

    Warning! When you specify Write mode, any existing content in the file is discarded.

  • "A" (Append mode): opens the file for writing, starting at the end. Any existing content is retained.

  • "U" (Update mode): opens the file for reading or writing, starting at the beginning of the file. Any existing content is retained. Use this mode and the GetPosition and SetPosition methods to maintain checkpoints of the current read/write position in the file.

    In Update mode, any write operation clears the file of all data that follows the position you set.

    Note: Currently, the effect of the Update mode and the GetPosition and SetPosition methods is not well defined for Unicode files. Use the Update mode only on files stored with a non-Unicode character set.

  • "E" (Conditional "exist" read mode): opens the file for reading only if it exists, starting at the beginning. If it doesn’t exist, the Open method has no effect. Before attempting to read from the file, use the IsOpen property to confirm that it’s open.

  • "N" (Conditional "new" write mode): opens the file for writing, only if it doesn’t already exist. If a file by the same name already exists, the Open method has no effect. Before attempting to write to the file, use the IsOpen property to confirm that it’s open. You can insert an asterisk (*) in the file name to ensure that a new file is created. The system replaces the asterisk with numbers starting at 1 and incrementing by 1, and checks for the existence of a file by each resulting name in turn. It uses the first name for which a file doesn’t exist. In this way you can generate a set of automatically numbered files. If you insert more than one asterisk, all but the first one are discarded.

charset

A string indicating the character set you expect when you read the file, or the character set you want to use when you write to the file. You can abbreviate Unicode UCS-2 to "U" and the host operating system's default non-Unicode (sometimes referred to as the ANSI character set) to “A”. All other character sets must be spelled out in full, for example, ASCII, Big5, Shift-JIS, UTF8, or UTF8BOM.

If “A” is specified as the character set, or you do not specify a character set, the character set used is dependent on the application server configuration. On a Windows application server, the default non-Unicode character set is dependent on the Windows ANSI Codepage (ACP) which can be checked using the DOS command chcp. On a Unix application server, the default non-Unicode character set is specified in the application server configuration file, psappsrv.cfg, and can be modified using PSADMIN. You can also use a record field value to specify the character set (for example, RECORD.CHARSET.)

A list of supported character set names valid for this argument can be found in PeopleTools: Global Technology.

See Character Sets Across the Tiers of the PeopleSoft Architecture.

Note: If you attempt to read data from a file using a different character set than was used to write that data to the file, the methods used generate a runtime error or the data returned is unusable.

When a file is opened for reading using the “U” charset argument, GetFile expects the file to begin with a Unicode byte order mark (BOM). This mark indicates whether the file is written in big endian order or little endian order. A BOM consisting of the hex value 0xFEFF indicates a big endian file, a BOM consisting of the hex value 0xFFEF indicates a little endian file. If the Unicode UCS-2 file being opened does not start with a BOM, an error is returned. The BOM is automatically stripped from the file when it is read into the buffers by GetFile.

When a file is opened for writing using the “U” charset argument, the appropriate Unicode BOM is automatically written to the start of the file depending on whether the application server hardware platform operates in little endian or big endian mode.

BOMs are only expected or supported for files in Unicode character sets such as UTF8, UTF8BOM, and UCS2. For consuming applications that do expect the BOM for UTF-8 files, the UTF8BOM character set is to create UTF-8 files with the BOM.

Note: For example, the UTF-8 BOM is represented by the sequence 0xEF BB BF. This sequence can be misinterpreted by a non-Unicode character set such as ISO-8859-1 and appears as ISO characters .

When working with XML documents, specify UTF8 or UTF8BOM for charset. If you are writing an XML file using a different character set, you must remember to include a character set declaration in the XML file.

In some cases, a Unicode file (UCS-2 or UTF-8) cannot be opened. An error message is displayed, when one of the following error conditions is encountered:

  • If the character set is U (that is, UCS2) and the mode is:

    • A: The file is empty or the BOM is missing or incorrect.

    • R: The BOM is missing or incorrect.

    • W: The file does not exist, or adding the BOM failed.

  • If the character set is UTF8 or UTF8BOM and the mode is:

    • R: For UTF8BOM, the BOM is missing or the file is empty; for UTF8, the file is empty.

    • A or W: For UTF8BOM only, the file does not exist or adding the BOM failed.

pathtype

If you have prepended a path to the file name, use this parameter to specify whether the path is an absolute or relative path. The valid values for this parameter are:

  • %FilePath_Relative (default)

  • %FilePath_Absolute

If you don’t specify pathtype the default is %FilePath_Relative.

If you specify a relative path, that path is appended to the path constructed from a system-chosen environment variable. A complete discussion of relative paths and environment variables is provided in documentation on the File class.

See Working With Relative Paths.

If the path is an absolute path, whatever path you specify is used verbatim. You must specify a drive letter and the complete path. You can’t use any wildcards when specifying a path.

The Component Processor automatically converts platform-specific separator characters to the appropriate form for where your PeopleCode program is executing. On a Windows system, UNIX "/" separators are converted to "\", and on a UNIX system, Windows "\" separators are converted to "/".

Note: The syntax of the file path does not depend on the file system of the platform where the file is actually stored; it depends only on the platform where your PeopleCode is executing.

Returns

None.

Example

The following example opens an existing UCS-2 file for reading:

&MYFILE.Open(&SOMENAME, "E", "U");
If &MYFILE.IsOpen Then
   while &MYFILE.ReadLine(&SOMESTRING)
      /* Process the contents of each &SOMESTRING */
   End-While;
   &MYFILE.Close();
End-If;

The following example opens a numbered file for writing in ANSI format, without overwriting any existing files:

&MYFILE.Open("C:\temp\item*.txt", "N", %FilePath_Absolute);
If &MYFILE.IsOpen Then
   &MYFILE.WriteLine("Some text.");
   &MYFILE.Close();
End-If;

Syntax

ReadLine(string)

Description

The ReadLine method reads one line of text from the external file. The line includes the newline character, but ReadLine strips out the newline character and inserts the result into the string variable string.

When ReadLine is executed, it moves the starting point for the next read operation to the end of the text just retrieved, so each line in the file can be read in turn by subsequent ReadLine operations. When no more data remains to be read from the file, ReadLine returns False, and clears the string variable of any content.

When the file object has been instantiated using a Unicode character set (UTF8, UTF8BOM, or UCS2) and the file has a Unicode byte order mark (BOM), the BOM is recognized as file metadata and is not treated as text. However, when the file has been instantiated using a non-Unicode character set and the file has a Unicode BOM, this is likely a user error; the BOM is treated as text and is not recognized as file metadata.

Parameters

Field or Control

Definition

string

A string variable that receives the input text.

Returns

A Boolean value: True if the method succeeds, False otherwise. The return value is not optional, it is required.

Example

The following example reads a file called &MYFILE and puts each line as a separate element in an array.

Local File &MYFILE;
Local array of string &MYARRAY;
Local string &TEXT;

&MYFILE = GetFile("names.txt", "R", "UTF8BOM");
&MYARRAY = CreateArrayRept("", 0);
While &MYFILE.ReadLine(&TEXT);
   &MYARRAY.Push(&TEXT);
End-While;
&MYFILE.Close();

Syntax

ReadRowset()

Description

The ReadRowset method is a file layout method. It instantiates a PeopleCode rowset object based on the file layout definition, then populates the rowset with one transaction from the file. A transaction is considered to be one instance of level zero data contained in a file record, plus all of its subordinate data. If you put more than one segment at level zero, each segment is read in sequence.

Note: You must specify a file layout using the SetFileLayout method before using ReadRowset, otherwise it will return NULL.

When ReadRowset is executed, it moves the starting point for the next read operation to the beginning of the next rowset, so each transaction in the file can be read in turn by subsequent ReadRowset operations. When no more data remains to be read from the file, ReadRowset returns NULL.

If you’re using the SetFileId method with ReadRowset to process an input file based on multiple file layouts, ReadRowset returns NULL when it reads a FileId file record (line) between the rowsets.

When ReadRowset returns NULL, you can use the IsFileId property to determine if you’ve reached the end of the file or a FileId record.

Note: When using ReadRowset, if a value in the file exceeds the defined length in the file layout, it is ignored. The given record field is flagged with an edit error which can be programmatically checked.

If the ReadRowset encounters a line in the file containing the FileId, and the lines following this are not a new rowset, the process considers it to be an invalid FileId. You can specify whether to ignore the invalid record or terminate the PeopleCode with the IgnoreInvalidId property.

Note: If you’re using the SetFileId method with ReadRowset to process an input file based on multiple layouts, FileId file records between the rowsets are considered to be valid file records, and won’t generate any errors, regardless of the state of the IgnoreInvalidId property.

See SetFileLayout.

Considerations for Using Dates With ReadRowset

Single digits in dates in the form MMDDYY or MMDDYYYY must be padded with zeros. That is, if the date in your data is February 3, 2000, the form must be:

02/03/2000 

or

02/03/00

The following is not valid.

2/3/00

Considerations for Using XML With ReadRowset

If all of the fields in the file layout are not present in the XML, no data is written to the database. If there are additional tags in the XML, they are ignored.

Considerations for Using Nested Data with ReadRowset

If you are processing input files with a large amount of nested data, your application server may run out of memory before the system finishes processing all of the data.

This may happen because of the differences between processing a single-level rowset and a multi-level rowset. If you are reading the rows of a single-level (level 0) rowset from a file, the file is processed one row at a time, that is, only one row resides in memory at a time.

However, if you are reading the rows of a multi-level (parent-child) rowset from a file, then for each level 0 row, all of the associated child rows (and all of their associated child rows) simultaneously reside in memory. As a result, during the processing a large input data file that is associated with a multi-level rowset (through a multi-level file layout definition), your application server may run out of memory.

To work around this, consider doing one of the following:

  • Retain your original file layout definition and split the original input file into smaller (but structurally unchanged) pieces

  • Flatten out your original file layout definition (that is, split it up into several single-level definitions) as well as split the original input file into several single-level pieces.

Considerations for Using Default Values with ReadRowset

The system variables related to date and time (for example, %Date, %Time, and %DateTime) cannot be used to specify the value of the Default Value property of a file layout field. This topic is covered in detail in the Application Designer PeopleBook.

See Specifying File Field Properties

Parameters

None.

Returns

A populated rowset.

Example

The following example reads and processes an entire file. The data in the file is based on a single File layout definition:

&MYFILE.GetFile(&SOMENAME, "R");
If &MYFILE.SetFileLayout(FILELAYOUT.SOMELAYOUT) then
   &SOMEROWSET = &MYFILE.ReadRowset();
   While &SOMEROWSET <> NULL
      /* Process the contents of each &SOMEROWSET */
      &SOMEROWSET = &MYFILE.ReadRowset();
   End-While;
End-If;
&MYFILE.Close();

Syntax

SetFileId(fileid, position)

Description

The SetFileId method is a file layout method. If your input file contains data based on more than one File Layout definition, you must use this method in combination with the CurrentRecord and IsNewFileId properties and the ReadRowset method to process the file correctly.

Note: SetFileId, CurrentRecord and IsNewFileId don’t apply to CSV and XML format input files. You can use only fixed format files to implement multiple file layouts.

See CurrentRecord, IsNewFileId, ReadRowset.

At each point in the input file where the structure of the rowset changes, there must be an extra line in the file containing the file record (line), the FileId file record (line), that signifies that the change. Each FileId file record must have the following components:

  • A value that designates it as a Fileid. Only one FileId value is necessary throughout the file, such as "999".

  • A name field that identifies the file layout needed for the rowset that follows. This field could contain the name of the file layout as it’s defined in Application Designer.

These lines containing the FileId are not part of any rowset. They can contain other information, which will be disregarded by the system. The FileId identifier and the file layout names aren’t automatically stored anywhere; they exist only in the input file’s FileId file records and in the PeopleCode.

To process an input file that requires multiple file layouts:

  1. Use SetFileLayout to specify the file layout definition to use.

    If you’re specifying the initial file layout for this file, it doesn’t have to be the correct one. You can determine the correct file layout to use for the first rowset during a subsequent step.

  2. Use SetFileId to specify the value of the FileId field, fileid, that’s used throughout the file to designate FileId file records.

    Note: After each execution of SetFileLayout, the SetFileId setting is disabled. Be sure to re-specify the FileId value if you expect the file layout to change, so the system continues looking for the next FileId file record.

  3. Use ReadRowset to read the next rowset from the file.

    The current file record is also stored in the CurrentRecord property as a string. The PeopleCode process determines whether it’s the beginning of a new rowset, or a FileId file record according to the fileid you specified. If it’s a FileId file record, the process sets the IsNewFileId property to True; if not, it sets the IsNewFileId property to False.

    Note: If this is the first execution of ReadRowset on the file, it returns NULL upon encountering the initial FileId file record, but still stores that file record in CurrentRecord and sets IsNewFileId accordingly.

  4. If the rowset returned isn’t NULL, process that rowset as necessary.

  5. If IsNewFileId is False, go back to step 3 to continue reading rowsets from the file. If IsNewFileId is True, examine CurrentRecord to determine which new file layout to use, and go back to step 1.

You can repeat this procedure one rowset at a time, proceeding through the remainder of the input file. When ReadRowset returns NULL, no more rowset data is available.

Parameters

Field or Control

Definition

fileid

Specify the value of the FileId field used in the current file.

position

Specify the column in the FileId file record where the FileId field starts. The default is 1.

Returns

None.

Example

&rsFile = &MYFILE.ReadRowset();
&CurrentRecord = &MYFILE.CurrentRecord;
&IsNewFileID = &MYFILE.IsNewFileId;
If &MYFILE.IsNewFileId Then
   &FILELAYOUT = FindFileID(&CurrentRecord);
   &MYFILE.SetFileLayout(@("FileLayout." | &FILELAYOUT));
   &MYFILE.SetFileId("999", 1);
End-If;

Syntax

SetFileLayout(FILELAYOUT.filelayoutname)

Description

The SetFileLayout method is a file layout method. It associates a specific file layout definition with the file object executing this method, providing easy access to rowset data. The file object must be associated with an open file. With file layout definitions, you can read and write rowsets as easily as strings. If the file object isn’t open or the definition doesn’t exist, SetFileLayout fails.

You must execute SetFileLayout before you can use any other file layout methods or properties with a file object, otherwise those methods and properties return NULL or False.

Note: All provided PeopleTools records that have a prefix of PSFLD are related to file layout definitions.

Parameters

Field or Control

Definition

filelayoutname

Specify as a string the name of an existing file layout definition created in Application Designer.

Returns

A Boolean value: True if the method succeeds, False otherwise.

Example

The following example opens a data file, associates a file layout definition with it, reads and processes the first rowset from it, and closes the file.

&MYFILE.Open(&SOMENAME, "E");
If &MYFILE.SetFileLayout(FILELAYOUT.SOMELAYOUT) then
   &SOMEROWSET = &MYFILE.ReadRowset();
   /* Process the contents of &SOMEROWSET */
Else
   /* Error - SetFileLayout failed */
End-If;
&MYFILE.Close();

Syntax

SetPosition(position)

Description

The SetPosition method sets the current read or write position in the external file associated with the file object executing this method. SetPosition works only with a file, which is opened in Update mode, and is designed to be used in combination with the GetPosition method to recover from interruptions during file access.

To start reading or writing from the beginning of a file, you must use SetPosition to set a read/write position of 0, immediately after you open the file in Update mode.

Parameters

Field or Control

Definition

position

The byte position in the file at which you want to continue reading or writing. This should either be 0 or a value you previously obtained with the GetPosition method and saved in a separate file or a database.

Warning! In Update mode, any write operation clears the file of all data that follows the position you set.

Note: Use SetPosition only for recovering from file access interruptions. Supplying your own value for SetPosition isn’t recommended, except for position 0.

Returns

None.

Example

The following example reopens a file in Update mode, and sets the read position to the last saved checkpoint:

&MYFILE = GetFile(&SOMENAME, "U");
If &MYFILE.IsOpen Then
   /* Retrieve the value of the last saved checkpoint, &LASTPOS */
   &MYFILE.SetPosition(&LASTPOS);
   while &MYFILE.ReadLine(&SOMESTRING)
      /* Process the contents of each &SOMESTRING */
   End-While;
   &MYFILE.Close();
End-If;

Note: Currently, the effect of the Update mode and the GetPosition and SetPosition methods is not well defined for Unicode files. Use the Update mode only on files stored with a non-Unicode character set.

Syntax

SetRecTerminator(Terminator)

Description

The SetRecTerminator method is a file layout method.

Use this method to specify the string of characters that indicate the end of a file record. Read operations use the value of SetRecTerminator to determine where each file record ends and the next one starts, and write operations append the value of SetRecTerminator to each record written.

This value defaults to the newline character appropriate to the platform where the file is being stored:

  • a linefeed on UNIX systems

  • a carriage return/linefeed combination on Windows systems

You need to specify a different record terminator only if you anticipate that part of the data in a file field that includes the newline character used on the storage platform; you must assign the record terminator a unique string that you know does not appear in a file field.

If you set the record terminator to Null ("") you eliminate linefeeds or carriage returns.

Note: The segment terminator of a file record isnot the same as its record terminator. The segment terminator occurs immediately after a single row of data; it is defined only at design time in the File Layout Designer. The record terminator occurs immediately after the segment terminator; it is defined only at runtime by the SetRecTerminator method of the File class.

See Specifying File Record Properties for information on the segment terminator.

Parameters

Field or Control

Definition

Terminator

Specify the value you want used for the record terminator.

Returns

None.

Example

&File = GetFile(......);

if &File.IsOpen then
   /* set the terminator to be NULL */
   Local String &Term = ""; 
   &File.SetRecTerminator(&Term);

Syntax

WriteBase64StringToBinary(encoded_string)

Description

Use this method to decode the input string using Base64 and write the resulting bytes to the output file associated with the current File object.

Parameters

Field or Control

Definition

encoded_string

Specifies a Base64-encoded string.

Returns

None.

Example

Local File &F1;
Local string &base64string;

/* Load the Base64 string data into &base64string */
&base64string = "...";

&F1 = GetFile("D:\anImage.jpg", "W", %FilePath_Absolute);
If &F1.IsOpen Then
   &F1.WriteBase64StringToBinary(&base64string);
   &F1.Close();
End-If;

Syntax

WriteLine(string)

Description

The WriteLine method writes one string of text, string, to the output file associated with the file object executing this method, followed by a newline character appropriate to the platform where the file is being written. To build a single line using multiple strings, use the WriteString method.

When the file object has been instantiated using a Unicode character set (UTF8, UTF8BOM, or UCS2) and the file has a Unicode byte order mark (BOM), the BOM is recognized as file metadata and is not treated as text. However, when the file has been instantiated using a non-Unicode character set and the file has a Unicode BOM, this is likely a user error; the BOM is treated as text and is not recognized as file metadata.

For writing UTF-8 files, use the UTF8BOM character set when instantiating the file object to include the Unicode BOM in output. Alternatively, use the UTF8 character set when instantiating the file object to exclude the BOM in output. Specify the character set depending on what the consuming application expects. When in doubt, use UTF8BOM to include the BOM. If the consuming application is the File class ReadLine method, either option will work. For clarity, always specify the charset parameter for calls to GetFile, GetTempFile, or Open, and match up charset with the character set used for writing and reading the file’s content.

Parameters

Field or Control

Definition

string

The string of text to be written.

Returns

None.

Example

The following example adds a line of text to an existing file:

&MYFILE.Open("somefile.txt", "A", "UTF8BOM");
&MYFILE.WriteLine("This is the last line in the file.");
&MYFILE.Close();

The following example converts a file where the fields are separated with tabs into a file where the fields are separated with commas.

Local File &TABFILE, &CSVFILE;
Local string &FILE_NAME, &DATA, &NEWDATA;

&FILE_NAME = "Test.txt";
&TAB = Char(9);

&TABFILE = GetFile(&FILE_NAME, R", "UTF8BOM");
&FileName = &TABFILE.Name;
&POS = Find(".", &FileName);
&NEWFILE_NAME = Substring(&FileName, 1, &POS) | "dat";
&CSVFILE = GetFile(&NEWFILE_NAME, "N", %FilePath_Absolute);
If &TABFILE.IsOpen And
      &CSVFILE.IsOpen Then
   While &TABFILE.ReadLine(&DATA);
      &NEWDATA = Substitute(&DATA, &TAB, ",");
      &CSVFILE.WriteLine(&NEWDATA);
   End-While;
   &TABFILE.Close();
   &CSVFILE.Close();
End-If;

Syntax

WriteRaw(RawBinary)

Description

The WriteRaw method writes the contents of RawBinary to a file. This can be used for writing images, messages, or other types of raw binary data to a file.

Parameters

Field or Control

Definition

RawBinary

Specify the raw binary to be written to the file.

Returns

None.

Example

The following example writes employee photos (GIF files) from a record to a file.

Local File &FILE;
Local Record &REC;
Local SQL &SQL;

&REC = CreateRecord(Record.EMPL_PHOTO);
&SQL = CreateSQL("%SelectAll(:1)", Record.EMPL_PHOTO);

&FILE = GetFile("C:\temp\EMPL_PHOTO.GIF", "w", "a", %FilePath_Absolute);

While &SQL1.Fetch(&REC)
   &FILE.WriteRaw(&REC.EMPLOYEE_PHOTO.Value);
End-While;
&FILE.Close();

Syntax

WriteRecord(record)

Description

The WriteRecord method is a file layout method. It writes the contents of the record object record, to the output file. (Remember, a record object contains only one row of data from an SQL table.)

You can use this method to build a transaction in the output file, one file record at a time, without having to instantiate and populate a rowset object. You can apply this method to any record whose structure and name matches that of a record defined in the current file layout.

Note: You must execute the SetFileId method from the file object before using WriteRecord, otherwise it returns False.

See SetFileLayout.

Note: When you're writing text to an XML file, special HTML characters, such as ampersands, lesser than or greater than symbols, and so on, are automatically converted to valid XML character string, such as &amp.

Considerations Using XML With File Definition Tags

File Definition Tags have no effect when importing data. However, generally, during export, the File Definition Tag is added at the start and end of the data to create a valid XML file.

The one exception is when the file to which the data is being written during export has been opened in append mode. At that time, the file definition tag is not taken into consideration.

Considerations Using XML with File Definitions

If your file layout is defined as XML, WriteRecord doesn't add the closing tag for the record. You must write it yourself using the WriteLine method. This is because the code has no way of knowing when you want to write children records following the record just written out.

The following code shows an example of using WriteLine:

Local File &MYFILE; 

&MYFILE = GetFile("XMLrecord.txt", "A"); 

If &MYFILE.IsOpen Then 
   If &MYFILE.SetFileLayout(FILELAYOUT.RECORDLAYOUT) Then 
      &LN = CreateRecord(RECORD.QA_INVEST_LN); 
      &SQL2 = CreateSQL("%Selectall(:1)", &LN); 
      While &SQL2.Fetch(&LN) 
         &MYFILE.WriteRecord(&LN); 
         WriteLine("</QA_INVEST_LN>"); /* Add the closing tag */ 
      End-While; 
   Else 
   /* do error processing - filelayout not correct */ 
   End-If; 
Else 
/* do error processing - file not open */ 
End-If; 

&MYFILE.Close(); 

Parameters

Field or Control

Definition

record

Specify the name of an existing record object to be written. You can use Rowset class methods such as GetField and built-in functions such as GetRecord to populate the record with data before writing it to the file.

Returns

A Boolean value: True if the method succeeds, False otherwise. This value is optional.

Example

The following example appends all the data in a record to an existing file:

Local File &MYFILE;

&MYFILE = GetFile("record.txt", "A");

If &MYFILE.IsOpen Then
   If &MYFILE.SetFileLayout(FILELAYOUT.VOL_TEST) Then
      &LN = CreateRecord(RECORD.VOLNTER_ORG_TBL);
      &SQL2 = CreateSQL("%Selectall(:1)", &LN);
      While &SQL2.Fetch(&LN) 
         &MYFILE.WriteRecord(&LN);
      End-While;
   Else
      /* do error processing - filelayout not correct */
   End-If;
Else
   /* do error processing -; file not open */
End-If;

&MYFILE.Close();

Syntax

WriteRowset(rowset [, Write_Data])

Description

The WriteRowset method is a file layout method. It writes the contents of a rowset object, rowset, to the output file associated with the file object executing this method. Regardless of whether the rowset contains just one or more than one transaction (level zero row), executing this method once writes the entire contents of the rowset to the output file.

Note: You must execute the SetFileLayout method from the file object before using WriteRowset, otherwise it returns False.

See SetFileLayout.

WriteRowset writes a rowset to a file only if the data in the component buffer has changed. You must specify the WriteData parameter as True if you want the WriteRowset method to force the rowset to be written to the file even if the buffer has not been changed.

Note: When you're writing text to an XML file, special HTML characters, such as ampersands, lesser than or greater than symbols, and so on, are automatically converted to valid XML character string, such as &amp.

Considerations Using Fixed Length Files With Numeric Fields

All numeric fields are right-justified in when writing to fixed length files. In addition, zeros are padded to the right after the decimal point if required.

Considerations Using XML With File Definition Tags

File Definition Tags have no effect when importing data. However, generally, during export, the File Definition Tag is added at the starting and end of the data to create a valid XML file.

The one exception is when the file to which the data is being written during export has been opened in append mode. At that time, the file definition tag is not taken into consideration.

Parameters

Field or Control

Definition

rowset

Specify the name of an existing rowset object that was instantiated with the File class CreateRowset or ReadRowset method. You can use Rowset class methods such as Select and built-in functions such as GetLevel0 to populate the rowset with data before writing it to the file.

WriteData

Specify whether to write the rowset data to the file whether or not the data in the buffer has changed. This parameter takes a Boolean value: True, write the data to the buffer regardless, False, only write the data if changed. The default value for this parameter is False.

Returns

A Boolean value: True if the method succeeds, False otherwise.

Example

Local File &MYFILE;
Local Rowset &FILEROWSET;

&MYFILE = GetFile("c:\temp\EMP_CKLS.txt", "A", %FilePath_Absolute);
If &MYFILE.IsOpen Then
   If &MYFILE.SetFileLayout(FILELAYOUT.EMPL_CHECKLIST) Then
      &FILEROWSET = &MYFILE.CreateRowset();
      &FILEROWSET = GetLevel0();
      &MYFILE.WriteRowset(&FILEROWSET, True);
   Else
      /* file layout not found, do error processing */
   End-If;
Else
   /* file not opened, do error processing */
End-if;

&MYFILE.Close();

Syntax

WriteString(string)

Description

The WriteString method writes one string of text to the output file associated with the file object executing this method, without any newline character. Each string written extends the current line in the file.

You can start a new line by using the WriteLine method to write the last part of the current line. WriteLine always adds a newline character appropriate to the platform where the file is being written, whether you supply a character string of any length, or a null string.

Parameters

Field or Control

Definition

string

A string variable containing the text to be written.

Returns

None.

Example

The following example opens an empty file, writes two lines of text to it without a final newline, and closes it:

&MYFILE.Open("somefile.txt", "W");
&MYFILE.WriteString("This is the first ");
&MYFILE.WriteString("line in the file.");
&MYFILE.WriteLine("");
&MYFILE.WriteString("This second line is not terminated.");
&MYFILE.Close();