ComposantsComponents

ComposantsComponents › Fichier › SortieFile › Output

tFileOutputPositional

tFileOutputPositional

Fichier › SortieFile › Output

Écrit les lignes d'un flux dans un fichier à positions fixes : chaque valeur occupe une largeur donnée, complétée par un caractère de remplissage ou coupée, sans séparateur entre les champs. Pour les fichiers d'échange à largeur fixe (banques, anciens systèmes), où chaque champ se lit à une position précise de la ligne. Writes the rows of a flow to a fixed-width file: each value takes a given width, completed with a padding character or cut, without a separator between the fields. For fixed-width exchange files (banks, legacy systems), where each field is read at a precise position of the line.

EntréeInput

Main un flux : les lignes à écrireone flow: the rows to write

SortieOutput

Main un flux, facultatif : les lignes repartent telles quellesone flow, optional: the rows go on unchanged

Déclencheurs en sortieOutput triggers

On Component Ok On Component Error Run if

UtilisationUsage

row1 (Main) row2 (Main) tDBInput_1 tMap_1 tFileOutputPositional_1

Le tMap prépare les colonnes dans l'ordre du fichier attendu ; le tFileOutputPositional donne à chacune sa largeur, une ligne du tableau Formats par colonne du schéma. The tMap prepares the columns in the order of the expected file; the tFileOutputPositional gives each one its width, one line of the Formats table per schema column.

  1. Déposez le tFileOutputPositional depuis la famille Fichier › Sortie de la palette. Drop the tFileOutputPositional from the File › Output family of the palette.
  2. Reliez-lui le flux à écrire (clic droit › Ligne › Main) : son schéma se remplit à partir du lien, et le tableau Formats prend une ligne par colonne. Connect the flow to write to it (right-click › Row › Main): its schema is filled from the link, and the Formats table gets one line per column.
  3. Dans Formats, donnez à chaque colonne sa Taille, son Caractère de remplissage, son Alignement, et choisissez dans Conserver ce qui reste d'une valeur trop longue. In Formats, give each column its Size, its Padding char, its Alignment, and choose in Keep what remains of a value that is too long.
  4. Indiquez le Nom de fichier, puis l'Encodage dans les paramètres avancés (ISO-8859-15 par défaut). Set the File Name, then the Encoding in the advanced settings (ISO-8859-15 by default).

Paramètres simplesBasic settings

Les libellés sont ceux de l'onglet Composant ; le nom technique, en gris, est celui du paramètre dans le fichier du job. Le nom de fichier et le séparateur de lignes sont des expressions Java : gardez les guillemets. Labels are those of the Component tab; the technical name, in grey, is the parameter name in the job file. The file name and the row separator are Java expressions: keep the quotes.

ParamètreSetting DéfautDefault VisibleShown Description
Type de propriétéProperty TypePROPERTY Built-inBuilt-In ToujoursAlways Built-in : les réglages sont saisis dans le composant. Référentiel : le nom du fichier, le séparateur de lignes, l'en-tête et l'encodage viennent d'une métadonnée de fichier positionnel du Référentiel. Built-In: the settings are typed in the component. Repository: the file name, the row separator, the header and the encoding come from a positional file metadata of the Repository.
Utiliser dynamique existantUse existing dynamicUSE_EXISTING_DYNAMIC NonNo ToujoursAlways Pour un schéma avec une colonne Dynamic : ses colonnes sont écrites avec les longueurs du schéma dynamique d'un tSetDynamicSchema, et avec la ligne Formats de la colonne Dynamic. Sans cette case, une colonne Dynamic n'écrit rien. D'après les modèles du composant, non essayé ici. For a schema with a Dynamic column: its columns are written with the lengths of the dynamic schema of a tSetDynamicSchema, and with the Formats line of the Dynamic column. Without this box, a Dynamic column writes nothing. From the component templates, not tried here.
Liste des composantsComponent ListDYNAMIC — Dynamique existant cochéExisting dynamic checked Le tSetDynamicSchema du job. S'il devine le schéma depuis un fichier, le composant s'arrête : tFileOutputPositional doesn't support to work with tSetDynamicSchema when 'Guess schema from file' option is activated. The tSetDynamicSchema of the job. If it guesses the schema from a file, the component stops: tFileOutputPositional doesn't support to work with tSetDynamicSchema when 'Guess schema from file' option is activated.
Utiliser le flux de sortieUse Output StreamUSESTREAM NonNo ToujoursAlways Écrit dans un flux Java (java.io.OutputStream) au lieu d'un fichier. À la fin, le composant vide le flux mais ne le ferme pas. Writes to a Java stream (java.io.OutputStream) instead of a file. At the end, the component flushes the stream but does not close it.
Flux de sortieOutput StreamSTREAMNAME outputStream Flux de sortie cochéOutput stream checked Une expression Java qui donne le flux : System.out, ou un flux rangé avant par un tJava, comme (java.io.OutputStream) globalMap.get("stream"). A Java expression that gives the stream: System.out, or a stream stored before by a tJava, such as (java.io.OutputStream) globalMap.get("stream").
Nom de fichierFile NameFILENAME chemin par défaut + /out.csvdefault path + /out.csv Flux de sortie décochéOutput stream unchecked Le fichier écrit : context.folder + "/out/people.txt". S'il existe, il est remplacé sans erreur (voir les exemples). The written file: context.folder + "/out/people.txt". If it exists, it is replaced with no error (see the examples).
SchémaSchemaSCHEMA — ToujoursAlways Les colonnes écrites, dans leur ordre, qui est celui des champs de la ligne. Elles viennent du lien entrant. The written columns, in their order, which is the order of the fields in the line. They come from the incoming link.
Séparateur de lignesRow SeparatorROWSEPARATOR "\n" ToujoursAlways Texte écrit après chaque ligne, tel quel : "\n" ou "\r\n". "" écrit toutes les lignes à la suite, sans fin de ligne. Text written after each row, as is: "\n" or "\r\n". "" writes all the rows one after the other, without line end.
Écrire à la suite deAppendAPPEND NonNo Flux de sortie décochéOutput stream unchecked Ajoute les lignes à la fin du fichier au lieu de le remplacer. L'en-tête n'est écrit que si le fichier est vide (voir l'exemple). Masque la compression. Adds the rows at the end of the file instead of replacing it. The header is only written if the file is empty (see the example). Hides the compression.
Inclure l'en-têteInclude headerINCLUDEHEADER NonNo ToujoursAlways Écrit d'abord une ligne avec le nom des colonnes, chacun mis en forme comme les valeurs de sa colonne : même largeur, même remplissage, même coupe. Avec un remplissage '0' à droite, id devient 00id. First writes a line with the column names, each one formatted like the values of its column: same width, same padding, same cut. With a '0' padding on the right, id becomes 00id.
Compresser en tant que fichier zipCompress as zip fileCOMPRESS NonNo Écrire à la suite décochéAppend unchecked Écrit une archive zip à la place du fichier : même nom avec l'extension .zip, qui contient une entrée au nom du fichier. D'après les modèles du composant ; voir l'exemple de tFileOutputDelimited, qui fait de même. Writes a zip archive instead of the file: same name with the .zip extension, holding one entry named after the file. From the component templates; see the example of tFileOutputDelimited, which does the same.
FormatsFORMATS une ligne par colonneone line per column ToujoursAlways La mise en forme de chaque colonne du schéma, dans son ordre : voir le tableau Formats ci-dessous. The format of each schema column, in its order: see the Formats table below.

Le tableau FormatsThe Formats table

Une ligne par colonne du schéma, que le Studio crée et range avec lui. Une valeur plus courte que sa taille est complétée selon l'alignement ; une valeur aussi longue ou plus longue suit Conserver. Une valeur nulle est écrite comme une valeur vide : la taille entière en caractères de remplissage. One line per schema column, which the Studio creates and orders with it. A value shorter than its size is completed according to the alignment; a value as long or longer follows Keep. A null value is written like an empty value: the whole size in padding characters.

ColonneColumn DéfautDefault VisibleShown Description
TailleSizeSIZE 10 ToujoursAlways Largeur du champ, en caractères (en octets avec Utiliser la longueur des octets comme cardinalité). Un nombre entier. Width of the field, in characters (in bytes with Use byte length as the cardinality). An integer.
Caractère de remplissagePadding charPADDING_CHAR ' ' ToujoursAlways Le caractère qui complète une valeur trop courte, entre apostrophes Java : ' ', '0', '*'. The character that completes a value that is too short, in Java single quotes: ' ', '0', '*'.
AlignementAlignmentALIGN GaucheLeft ToujoursAlways Gauche : la valeur, puis le remplissage (abc.....). Droite : le remplissage, puis la valeur (.....abc), l'habitude pour les nombres. Centre : le remplissage partagé, le caractère en trop à droite (..abc...). Left: the value, then the padding (abc.....). Right: the padding, then the value (.....abc), the habit for numbers. Center: the padding shared, the extra character on the right (..abc...).
ConserverKeepKEEP TousAll ToujoursAlways Ce qui reste d'une valeur plus longue que sa taille. Tous : toute la valeur, sans coupe ; la ligne est plus longue et les champs suivants se décalent. Gauche : le début (ABCD pour ABCDEFGHIJ en 4). Milieu : le milieu (DEFG). Droite : la fin (GHIJ). What remains of a value longer than its size. All: the whole value, not cut; the line is longer and the next fields shift. Left: the start (ABCD for ABCDEFGHIJ in 4). Middle: the middle (DEFG). Right: the end (GHIJ).

Paramètres avancésAdvanced settings

ParamètreSetting DéfautDefault VisibleShown Description
Séparateur avancé (pour les nombres)Advanced separator (for numbers)ADVANCED_SEPARATOR NonNo ToujoursAlways Écrit les nombres avec les deux séparateurs ci-dessous (1.250,50 au lieu de 1250.50), avant la mise à la taille : les séparateurs comptent dans la largeur. Writes numbers with the two separators below (1.250,50 instead of 1250.50), before sizing: the separators count in the width.
Séparateur de milliersThousands separatorTHOUSANDS_SEPARATOR "," Séparateur avancé cochéAdvanced separator checked Placé tous les trois chiffres de la partie entière. Placed every three digits of the integer part.
Séparateur décimalDecimal separatorDECIMAL_SEPARATOR "." Séparateur avancé cochéAdvanced separator checked Remplace le point décimal. Replaces the decimal point.
Utiliser la longueur des octets comme cardinalitéUse byte length as the cardinalityUSE_BYTE NonNo ToujoursAlways Compte les tailles en octets de l'Encodage au lieu de caractères. Ne change rien pour un encodage d'un octet par caractère (ISO-8859-15) ; en UTF-8, é compte pour deux. Une coupe peut alors tomber au milieu d'un caractère (voir l'exemple). Counts the sizes in bytes of the Encoding instead of characters. Changes nothing for a one-byte-per-character encoding (ISO-8859-15); in UTF-8, é counts for two. A cut can then fall in the middle of a character (see the example).
Créer le répertoire s'il n'existe pasCreate directory if does not existCREATE OuiYes Flux de sortie décochéOutput stream unchecked Crée le dossier du fichier, avec ses parents. Décochée, un dossier absent arrête le composant (voir les erreurs). Creates the folder of the file, with its parents. Unchecked, a missing folder stops the component (see the errors).
Personnaliser la taille de la mémoire tamponCustom the flush buffer sizeFLUSHONROW NonNo ToujoursAlways Vide la mémoire tampon dans le fichier toutes les N lignes (Nombre de lignes) au lieu d'attendre qu'elle soit pleine. D'après les modèles du composant, non essayé ici. Flushes the buffer to the file every N rows (Row number) instead of waiting for it to be full. From the component templates, not tried here.
Nombre de lignesRow numberFLUSHONROW_NUM 1 Taille personnalisée cochéeCustom size checked Le N ci-dessus. The N above.
Sortie en mode ligneOutput in row modeROW_MODE NonNo ToujoursAlways Utilise une mémoire tampon qui ne coupe jamais une ligne entre deux écritures (routines.system.BufferedOutput). D'après les modèles du composant, non essayé ici. Uses a buffer that never cuts a row between two writes (routines.system.BufferedOutput). From the component templates, not tried here.
EncodageEncodingENCODING "ISO-8859-15" ToujoursAlways L'encodage du fichier écrit. Le défaut n'est pas UTF-8 : é s'écrit E9. The encoding of the written file. The default is not UTF-8: é is written E9.
Ne pas générer de fichier videDon't generate empty fileDELETE_EMPTYFILE NonNo Flux de sortie décochéOutput stream unchecked Si aucune ligne n'a été écrite, supprime le fichier à la fin, même s'il contient l'en-tête. Un fichier qui existait déjà, complété avec Écrire à la suite de, est gardé. D'après les modèles du composant ; voir l'exemple de tFileOutputDelimited. If no row was written, deletes the file at the end, even if it holds the header. A file that already existed, completed with Append, is kept. From the component templates; see the example of tFileOutputDelimited.

Valeurs et variable globaleValues and global variable

Texte de chaque valeurText of each value

La valeur est d'abord mise en texte, puis mise à sa taille : The value is first turned into text, then brought to its size:

  • Date : selon le modèle de la colonne dans le schéma. Date: following the column pattern in the schema.
  • BigDecimal : arrondi à la précision de la colonne (au plus proche, 0,5 vers le haut), sans notation scientifique. BigDecimal: rounded to the column precision (half up), without scientific notation.
  • byte[] : décodé avec le jeu de caractères par défaut de Java, pas avec l'Encodage du composant. byte[]: decoded with the Java default character set, not with the component Encoding.
  • Valeur nulle : texte vide, donc la taille entière en remplissage. Null value: empty text, so the whole size in padding.
  • Autres types : leur texte Java (String.valueOf). Other types: their Java text (String.valueOf).

Variable globaleGlobal variable

NB_LINE (Integer, disponible après l'exécution du composant) : nombre de lignes écrites, en-tête non compté. NB_LINE (Integer, available after the component has run): number of rows written, header not counted.

((Integer) globalMap.get("tFileOutputPositional_1_NB_LINE"))

ExemplesExamples

Les chemins sont écrits à partir de la variable de contexte folder. Un tJava relié par On Subjob Ok affiche ensuite chaque ligne du fichier entre crochets, pour rendre visibles les espaces de fin. Les sorties sont celles de la console, copiées depuis une exécution du job. Paths are written from the folder context variable. A tJava connected with On Subjob Ok then prints each line of the file in brackets, to make the trailing spaces visible. The outputs are the console ones, copied from a run of the job.

Quatre colonnes, avec en-têteFour columns, with header

row1 (Main) OnSubjobOk tFixedFlowInput_1 tFileOutputPositional_1 tJava_2
idInteger nameString cityString amountBigDecimal, précisionprecision 2
1AdaLondon1250.5
2Margaretnull80
3AlanManchester3.14159
ColonneColumn TailleSize RemplissagePadding AlignementAlignment ConserverKeep
id4'0'DroiteRightTousAll
name6' 'GaucheLeftGaucheLeft
city10' 'CentreCenterTousAll
amount9' 'DroiteRightTousAll

Inclure l'en-tête coché, nom context.folder + "/out/people.txt". Avant lui, un premier tJava écrit old line dans ce fichier. Code du tJava_2 : Include header checked, name context.folder + "/out/people.txt". Before it, a first tJava writes old line to this file. tJava_2 code:

for (String line : java.nio.file.Files.readAllLines(java.nio.file.Paths.get(context.folder + "/out/people.txt"))) {
    System.out.println("[" + line + "]");
}
System.out.println("NB_LINE: " + globalMap.get("tFileOutputPositional_1_NB_LINE"));
[00idname     city      amount]
[0001Ada     London    1250.50]
[0002Margar              80.00]
[0003Alan  Manchester     3.14]
NB_LINE: 3
  • Chaque ligne fait 29 caractères (4 + 6 + 10 + 9), puis la fin de ligne \n. Each line is 29 characters long (4 + 6 + 10 + 9), then the \n line end.
  • L'en-tête suit les formats : id est complété par des 0. The header follows the formats: id is completed with 0.
  • Margaret est coupé à 6 caractères ; la ville nulle donne 10 espaces. Margaret is cut to 6 characters; the null city gives 10 spaces.
  • old line a disparu : le fichier existant est remplacé sans erreur. old line is gone: the existing file is replaced with no error.

Conserver et AlignementKeep and Alignment

Une colonne code, un composant par réglage. keep_… : valeur ABCDEFGHIJ, taille 4, chacun des quatre choix de Conserver. align_… : valeur abc, taille 8, remplissage '.', chacun des trois alignements. null : valeur nulle, taille 5, remplissage '*'. One code column, one component per setting. keep_…: value ABCDEFGHIJ, size 4, each of the four Keep choices. align_…: value abc, size 8, padding '.', each of the three alignments. null: null value, size 5, padding '*'.

for (String name : new String[] {"keep_All", "keep_Left", "keep_Middle", "keep_Right", "align_Left", "align_Center", "align_Right", "null"}) {
    String line = java.nio.file.Files.readAllLines(java.nio.file.Paths.get(context.folder + "/out/" + name + ".txt")).get(0);
    System.out.println(name + ": [" + line + "]");
}
keep_All: [ABCDEFGHIJ]
keep_Left: [ABCD]
keep_Middle: [DEFG]
keep_Right: [GHIJ]
align_Left: [abc.....]
align_Center: [..abc...]
align_Right: [.....abc]
null: [*****]

Avec Tous, le défaut, la valeur garde ses 10 caractères dans un champ de 4. With All, the default, the value keeps its 10 characters in a field of 4.

Caractères ou octetsCharacters or bytes

Valeur Café, remplissage '.', aligné à gauche. chars.txt : taille 6, UTF-8. bytes.txt : pareil, Utiliser la longueur des octets comme cardinalité coché. cut.txt : taille 4, octets, UTF-8, Conserver Gauche. latin.txt : taille 6, octets, encodage par défaut. Le tJava affiche les octets en hexadécimal : Value Café, padding '.', left aligned. chars.txt: size 6, UTF-8. bytes.txt: the same, Use byte length as the cardinality checked. cut.txt: size 4, bytes, UTF-8, Keep Left. latin.txt: size 6, bytes, default encoding. The tJava prints the bytes in hexadecimal:

for (String f : new String[] {"/out/chars.txt", "/out/bytes.txt", "/out/cut.txt", "/out/latin.txt"}) {
    StringBuilder sb = new StringBuilder();
    for (byte b : java.nio.file.Files.readAllBytes(java.nio.file.Paths.get(context.folder + f))) {
        sb.append(String.format("%02X ", b));
    }
    System.out.println(f.substring(f.lastIndexOf('/') + 1) + ": " + sb.toString().trim());
}
chars.txt: 43 61 66 C3 A9 2E 2E 0A
bytes.txt: 43 61 66 C3 A9 2E 0A
cut.txt: 43 61 66 EF BF BD 0A
latin.txt: 43 61 66 E9 2E 2E 0A
  • chars.txt : 4 caractères et 2 points, mais 7 octets avant la fin de ligne. chars.txt: 4 characters and 2 dots, but 7 bytes before the line end.
  • bytes.txt : é compte pour deux octets, il reste un point : 6 octets. bytes.txt: é counts for two bytes, one dot remains: 6 bytes.
  • cut.txt : la coupe à 4 octets tombe au milieu de é, qui devient U+FFFD (EF BF BD) : le champ fait 6 octets au lieu de 4. cut.txt: the cut at 4 bytes falls in the middle of é, which becomes U+FFFD (EF BF BD): the field is 6 bytes long instead of 4.
  • latin.txt : en ISO-8859-15, un octet par caractère, la case ne change rien. latin.txt: in ISO-8859-15, one byte per character, the box changes nothing.

Écrire à la suiteAppend

row1 (Main) OnSubjobOk row2 (Main) tFixedFlowInput_1 tFileOutputPositional_1 tFixedFlowInput_2 tFileOutputPositional_2

Mêmes formats que le premier exemple, en-tête coché, même fichier append.txt. Le premier composant écrit la ligne 1 ; le second, Écrire à la suite de coché, les lignes 2 et 3. Le tJava affiche le fichier en rendant visibles les fins de ligne : Same formats as the first example, header checked, same append.txt file. The first component writes row 1; the second one, Append checked, rows 2 and 3. The tJava prints the file with the line ends made visible:

String text = new String(java.nio.file.Files.readAllBytes(java.nio.file.Paths.get(context.folder + "/out/append.txt")));
System.out.print(text.replace("\r", "\\r").replace("\n", "\\n\n"));
00idname     city      amount\n
0001Ada     London    1250.50\n
0002Margar              80.00\n
0003Alan  Manchester     3.14\n

Le fichier n'étant pas vide, le second composant n'a pas répété l'en-tête. The file not being empty, the second component did not repeat the header.

ErreursErrors

Le nom du job est remplacé par MyJob, le dossier de travail par C:\data ; la trace d'exception est abrégée. La fin du message vient de Windows, dans sa langue. The job name is replaced with MyJob, the working folder with C:\data; the exception trace is shortened. The end of the message comes from Windows, in its language.

Dossier absentMissing folder

Nom context.folder + "/out/new/people.txt", dossier new absent, Créer le répertoire s'il n'existe pas décoché : le job s'arrête (code 1). Name context.folder + "/out/new/people.txt", new folder missing, Create directory if does not exist unchecked: the job stops (exit code 1).

Exception in component tFileOutputPositional_1 (MyJob)
java.io.FileNotFoundException: C:\data\out\new\people.txt (Le chemin d’accès spécifié est introuvable)
	at java.base/java.io.FileOutputStream.open0(Native Method)
	…

Conseils et limitesTips and limits

« Tous » ne coupe pas“All” does not cut

Avec Conserver sur Tous, le défaut, une valeur trop longue est écrite entière : les champs suivants se décalent et le fichier n'est plus lisible par position, sans aucune erreur. Pour garantir la largeur, choisissez Gauche (ou Droite pour garder la fin d'un numéro). With Keep on All, the default, a value that is too long is written whole: the next fields shift and the file can no longer be read by position, with no error at all. To guarantee the width, choose Left (or Right to keep the end of a number).

L'en-tête est mis en formeThe header is formatted

Les noms de colonnes reçoivent le remplissage, l'alignement et la coupe de leur colonne : 00id pour une colonne complétée de zéros, un nom coupé si la colonne est étroite. Si le destinataire attend un en-tête précis, écrivez-le autrement (tJava, ou un premier fichier écrit avant). The column names get the padding, alignment and cut of their column: 00id for a zero-filled column, a cut name if the column is narrow. If the receiver expects a precise header, write it another way (tJava, or a first file written before).

Largeurs en UTF-8Widths in UTF-8

Par défaut, la taille compte des caractères : en UTF-8, une ligne avec des accents fait plus d'octets que prévu. Si le destinataire compte des octets, cochez Utiliser la longueur des octets comme cardinalité, et évitez qu'une coupe tombe sur un caractère accentué. By default, the size counts characters: in UTF-8, a line with accents has more bytes than planned. If the receiver counts bytes, check Use byte length as the cardinality, and avoid a cut falling on an accented character.

Fichier remplacé sans erreurFile replaced with no error

Contrairement à tFileOutputDelimited, le composant n'a pas d'option d'erreur si le fichier existe : il le remplace à chaque exécution. Testez-le avant avec tFileExist s'il faut le protéger. Unlike tFileOutputDelimited, the component has no error option if the file exists: it replaces it at each run. Test it first with tFileExist if it must be protected.

Nombres complétés de zérosZero-filled numbers

Pour un champ numérique du type 0001, alignez à droite avec le remplissage '0'. Préparez en amont (tMap) le texte d'un montant si le destinataire attend un format sans point décimal. For a numeric field such as 0001, align right with the '0' padding. Prepare upstream (tMap) the text of an amount if the receiver expects a format without decimal point.

EncodageEncoding

Le défaut est ISO-8859-15. Réglez l'Encodage sur l'attente du destinataire, ou convertissez le fichier ensuite avec tChangeFileEncoding (la largeur en octets peut alors changer). The default is ISO-8859-15. Set the Encoding to what the receiver expects, or convert the file afterwards with tChangeFileEncoding (the width in bytes may then change).

Voir aussiSee also