说以下是我的文件内容(数百条相同的图案线)
1979,2013-08-07 19:03:35,abc,12345,310012
1980,2013-08-07 19:05:03,fds,12345,310160
.
.
我想读取文件并逐行扫描文件,并将该行的第4列(在所有行上重复的12345)替换为另一个值,并在每行的末尾添加一个新值。
最后,我需要使用更新的值作为输出重新生成文件。
这是我到目前为止所做的事情:
URL path = ClassLoader.getSystemResource("test.txt");
File file = new File(path.toURI());
try
{
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
// Here I need to do the replacement codes
}
scanner.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
将每一行拆分成一个数组并执行这样的流程或者有更好的解决方案是不是一个好主意?
我也不确定如何使用已编辑的内容创建输出。 任何帮助将不胜感激。
答案 0 :(得分:1)
我这样做是通过将每一行放入一个arraylist,在数组的每一行使用split(",")
,并替换每个数组中的第四个索引。要将数组重新加入字符串,您必须编写自己的函数(Java没有内置函数)。但是another stack overflow question解决了这个问题。
try
{
Scanner scanner = new Scanner(file);
// initialize the arraylist, which will hold the split strings
ArrayList<String[]> data = new ArrayList<String[]>();
while (scanner.hasNextLine())
{
// filling the arraylist
String line = scanner.nextLine();
String[] split = line.split(",");
data.add(split);
}
scanner.close();
// replacing the values
for (String[] split : data) {
split[3] = "new value";
}
// sloppily glueing everything back together
String output = "";
for (String[] split : data) {
for (int i = 0; i < 5; i++) {
if (i < 4) {output += datum + ",";}
else {output += datum;}
}
output += "\n";
}
return output;
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
可能真的很草率和低效,但这很合乎逻辑。
答案 1 :(得分:1)
您可以尝试这样的事情:
public void replace(final int column, final String replacement, final File file, final String... appends) throws IOException {
assert column >= 0 : "column < 0";
final List<String> lines = new LinkedList<String>();
final Scanner reader = new Scanner(file, "UTF-8");
while(reader.hasNextLine()){
final String line = reader.nextLine().trim();
if(line.isEmpty())
continue;
final String[] tokens = line.split(",");
assert column < tokens.length-1 : "column > tokens.length-1";
tokens[column] = replacement;
final StringBuilder builder = new StringBuilder();
for(final String token : tokens)
builder.append(token + ",");
for(final String append : appends)
builder.append(append + ",");
builder.deleteCharAt(builder.length()-1);
lines.add(builder.toString());
}
reader.close();
final BufferedWriter writer = new BufferedWriter(new FileWriter(file, false));
for(final String line : lines){
writer.write(line);
writer.newLine();
}
writer.flush();
writer.close();
}
或者如果你使用的是Java 8,你可以试试这样的东西:
public void replace(final int column, final String replacement, final File file, final String... appends) throws IOException {
assert column >= 0 : "column < 0";
final List<String> lines = new LinkedList<>();
final Scanner reader = new Scanner(file, "UTF-8");
while(reader.hasNextLine()){
final String line = reader.nextLine().trim();
if(line.isEmpty())
continue;
final String[] tokens = line.split(",");
assert column < tokens.length-1 : "column > tokens.length-1";
tokens[column] = replacement;
final List<String> temp = new LinkedList<>();
temp.addAll(Arrays.asList(tokens));
temp.addAll(Arrays.asList(appends));
lines.add(temp.stream().collect(Collectors.joining(",")));
}
reader.close();
final BufferedWriter writer = new BufferedWriter(new FileWriter(file, false));
lines.forEach(
l -> {
try{
writer.write(l);
writer.newLine();
}catch(IOException ex){
ex.printStackTrace();
}
}
);
writer.flush();
writer.close();
}
要调用此方法,您可以执行以下操作:
replace(3, "string to replace 12345", file, strings_you_want_to_append_to_the_end);
答案 2 :(得分:0)
您可以使用正则表达式执行此操作:
(?<=^[^,]+,[^,]+,[^,]+,)[^,]+
e.g:
private static final Pattern REGEX_PATTERN =
Pattern.compile("(?<=^[^,]+,[^,]+,[^,]+,)[^,]+");
public static void main(String[] args) {
// Open input file
// Open output file
// Read input line
String inputLine = "1979,2013-08-07 19:03:35,abc,12345,310012";
String outputLine = REGEX_PATTERN.matcher(input)
.replaceFirst("YOUR_REPLACEMENT");
// Print (only for debug)
System.out.println(
outputLine
); // prints "1979,2013-08-07 19:03:35,abc,YOUR_REPLACEMENT,310012"
// Write output line
// Close both files
}
答案 3 :(得分:0)
尝试以下
stringBuilder = new StringBuilder();
String[] resultArray = sCurrentval.split(",");
resultArray[3] = EDIT_VALVE; //your new value to replace
for (String s : resultArray)
{
stringBuilder.append(s);
stringBuilder.append(",");
}
sCurrentval = stringBuilder.append(LAST_VALUE).toString(); // add your last value