1行に115個の固定幅フィールドがあるベンダーからのファイルがあります。そのファイルを115フィールドに解析して、コードで使用できるようにするにはどうすればよいですか?
私の最初の考えは、のように、そしてを使用して、各フィールドの定数を作成するNAME_START_POSITIONことNAME_LENGTHですsubstring。それは醜いように見えるので、これを行うためのより良い方法に興味があります。グーグル検索で見つかったいくつかの図書館のどれも、これ以上良いとは思えなかった。
1行に115個の固定幅フィールドがあるベンダーからのファイルがあります。そのファイルを115フィールドに解析して、コードで使用できるようにするにはどうすればよいですか?
私の最初の考えは、のように、そしてを使用して、各フィールドの定数を作成するNAME_START_POSITIONことNAME_LENGTHですsubstring。それは醜いように見えるので、これを行うためのより良い方法に興味があります。グーグル検索で見つかったいくつかの図書館のどれも、これ以上良いとは思えなかった。
車輪を再発明する代わりに、 flatwormのようなフラット ファイル パーサーを使用します。クリーンな API があり、使いやすく、まともなエラー処理と単純なファイル形式記述子を備えています。別のオプションはjFFP ですが、私は最初のものを好みます。
uniVocity-parsers には と が付属してFixedWidthParserおりFixedWidthWriter、さまざまなフィールドやパディングなどを持つ行を含む、扱いにくい固定幅形式をサポートできます。
// creates the sequence of field lengths in the file to be parsed
FixedWidthFields fields = new FixedWidthFields(4, 5, 40, 40, 8);
// creates the default settings for a fixed width parser
FixedWidthParserSettings settings = new FixedWidthParserSettings(fields); // many settings here, check the tutorial.
//sets the character used for padding unwritten spaces in the file
settings.getFormat().setPadding('_');
// creates a fixed-width parser with the given settings
FixedWidthParser parser = new FixedWidthParser(settings);
// parses all rows in one go.
List<String[]> allRows = parser.parseAll(new File("path/to/fixed.txt")));
あらゆる種類の固定幅入力を解析するためのいくつかの例を次に示します。
また、一般的な書き込みの他の例と、固定幅形式に固有の他の固定幅の例を次に示します。
開示: 私はこのライブラリの作成者です。これはオープンソースで無料です (Apache 2.0 ライセンス)。
私はfixedformat4jで遊んだことがありますが、とてもいいです。コンバータなどの設定が簡単。
これが私が使用する基本的な実装です:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
public class FlatFileParser {
public static void main(String[] args) {
File inputFile = new File("data.in");
File outputFile = new File("data.out");
int columnLengths[] = {7, 4, 10, 1};
String charset = "ISO-8859-1";
String delimiter = "~";
System.out.println(
convertFixedWidthFile(inputFile, outputFile, columnLengths, delimiter, charset)
+ " lines written to " + outputFile.getAbsolutePath());
}
/**
* Converts a fixed width file to a delimited file.
* <p>
* This method ignores (consumes) newline and carriage return
* characters. Lines returned is based strictly on the aggregated
* lengths of the columns.
*
* A RuntimeException is thrown if run-off characters are detected
* at eof.
*
* @param inputFile the fixed width file
* @param outputFile the generated delimited file
* @param columnLengths the array of column lengths
* @param delimiter the delimiter used to split the columns
* @param charsetName the charset name of the supplied files
* @return the number of completed lines
*/
public static final long convertFixedWidthFile(
File inputFile,
File outputFile,
int columnLengths[],
String delimiter,
String charsetName) {
InputStream inputStream = null;
Reader inputStreamReader = null;
OutputStream outputStream = null;
Writer outputStreamWriter = null;
String newline = System.getProperty("line.separator");
String separator;
int data;
int currentIndex = 0;
int currentLength = columnLengths[currentIndex];
int currentPosition = 0;
long lines = 0;
try {
inputStream = new FileInputStream(inputFile);
inputStreamReader = new InputStreamReader(inputStream, charsetName);
outputStream = new FileOutputStream(outputFile);
outputStreamWriter = new OutputStreamWriter(outputStream, charsetName);
while((data = inputStreamReader.read()) != -1) {
if(data != 13 && data != 10) {
outputStreamWriter.write(data);
if(++currentPosition > (currentLength - 1)) {
currentIndex++;
separator = delimiter;
if(currentIndex > columnLengths.length - 1) {
currentIndex = 0;
separator = newline;
lines++;
}
outputStreamWriter.write(separator);
currentLength = columnLengths[currentIndex];
currentPosition = 0;
}
}
}
if(currentIndex > 0 || currentPosition > 0) {
String line = "Line " + ((int)lines + 1);
String column = ", Column " + ((int)currentIndex + 1);
String position = ", Position " + ((int)currentPosition);
throw new RuntimeException("Incomplete record detected. " + line + column + position);
}
return lines;
}
catch (Throwable e) {
throw new RuntimeException(e);
}
finally {
try {
inputStreamReader.close();
outputStreamWriter.close();
}
catch (Throwable e) {
throw new RuntimeException(e);
}
}
}
}
固定長フォーマット用の適切なライブラリがないという事実にうんざりしていたので、独自に作成しました。ここで確認できます: https://github.com/atais/Fixed-Length
基本的な使用法は、ケース クラスを作成することであり、それはHList(Shapeless) として記述されます。
case class Employee(name: String, number: Option[Int], manager: Boolean)
object Employee {
import com.github.atais.util.Read._
import cats.implicits._
import com.github.atais.util.Write._
import Codec._
implicit val employeeCodec: Codec[Employee] = {
fixed[String](0, 10) <<:
fixed[Option[Int]](10, 13, Alignment.Right) <<:
fixed[Boolean](13, 18)
}.as[Employee]
}
また、行を簡単にデコードしたり、オブジェクトをエンコードしたりできます。
import Employee._
Parser.decode[Employee](exampleString)
Parser.encode(exampleObject)
/*The method takes three parameters, fixed length record , length of record which will come from schema , say 10 columns and third parameter is delimiter*/
public class Testing {
public static void main(String as[]) throws InterruptedException {
fixedLengthRecordProcessor("1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10", 10, ",");
}
public static void fixedLengthRecordProcessor(String input, int reclength, String dilimiter) {
String[] values = input.split(dilimiter);
String record = "";
int recCounter = 0;
for (Object O : values) {
if (recCounter == reclength) {
System.out.println(record.substring(0, record.length() - 1));// process
// your
// record
record = "";
record = record + O.toString() + ",";
recCounter = 1;
} else {
record = record + O.toString() + ",";
recCounter++;
}
}
System.out.println(record.substring(0, record.length() - 1)); // process
// your
// record
}
}