我有一个平面文件,我正在尝试清理该文件以导入数据库。布局不一致,但始终包含一个字段名称(可变长度文本,但始终是 9 个单词或短语之一),后跟一个自由格式文本字段(可变长度最多 1024 字节)。我需要提取 1024 字节字段,并将它们排列成跨字段名称的列。
输入文件:
foo-01 bunches of data
foo bar01 more bunches of data including a bunch of notes
foo-01 lots of data lives in this field
foo18 monday notes
...etc.
输出文件 - 分隔,修剪空格
foo-01;foo bar 01;foo18 (<-- header row)
bunches of data; more bunches of data including a bunch of notes; ;
lots of data lives in this field; ; notes
我的策略是这样的:阅读每一行。如果该行以九个字段名之一开头,我会将一个子字符串(字段名后面的第一个字符到行中最后一个字符 - 空格被修剪)写入到分隔平面文件中适当的列位置。
这段代码有效,
if(inputLine.startsWith("foo-01"))
{
String lineVal = inputLine.trim();
int lVLen = lineVal.length();
String outVal = lineVal.substring(17,lVLen);
String outValTrim = outVal.trim();
System.out.println(evalVal+" "+inputLine+" "+outValTrim);
}
else
...etc...
但提出了问题。
考虑:
String outValTrim = inputLine.trim().substring(17,inputLine.trim().length()).trim();
我最多可以使用多少种方法?例如,
foo = Stringmethod1.Stringmethod2.StringMethod3()
语句中方法的顺序有规则吗?
在一个语句中组合方法的最佳实践是什么?我 感觉它的可读性较差,而且我不确定效率。
最佳答案
一个方法的最大大小为 64K,您不能使用比这更多的方法。您可能还会发现您不需要链接尽可能多的方法。
String outValTrim = inputLine.trim().substring(17).trim()
我怀疑第一个trim()不正确......
最佳实践是使代码尽可能可读且易于理解。
效率很少是最重要的问题,除非你能证明例如通过使用探查器,这就是您遇到问题的原因,请坚持可读性。
关于java - 在变量上使用多个 String 方法的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10452070/