所以我正在处理一个问题,我将文本从记事本导入java并尝试将其放入csv文件中。我已成功设法这样做,但现在我需要从csv中的每行数组中删除信息。
所以为了帮助想象这样的东西:
Name = Bob, Age = 42, FavColor = Blue
Name = Clarice, Age = 20, FavColor = Red
Name = John, Age = 34, FavColor = Green
我想从csv的每个部分删除Name =,Age =和FavColor =以便我只有相关数据。看起来像这样:
Bob, 42, Blue
Clarice, 20, Red
John, 34, Green
为了进一步了解我正在做什么,我的代码到目前为止看起来像这样:
public static void main(String[] args) throws IOException{
String file_name = "C:/Users/etc....";
PrintWriter pw = new PrintWriter(new File("test.csv"));
StringBuilder sb = new StringBuilder();
try {
ReadFile file = new ReadFile(file_name);
String[] aryLines = file.OpenFile();
sb.append("Name");
sb.append(',');
sb.append("Age");
sb.append(',');
sb.append("FavColor");
sb.append('\n');
int i;
for(i = 0; i < aryLines.length; i++) {
sb.append(aryLines[i]);
sb.append("\n");
}
pw.write(sb.toString());
pw.close();
System.out.println("CSV Written");
}
catch (IOException e) {
System.out.println( e.getMessage() );
}
}
数组正在通过记事本信息的每一行,但我只是被困在如何删除信息。任何帮助,将不胜感激。谢谢!
答案 0 :(得分:0)
由于这很简单,我会给你一个概述:
,
拆分,您将得到一个包含3个字符串的数组=
分割,您将得到一个包含2个字符串的数组。拿第二个字符串trim()
StringBuilder
对象,这可能会耗尽内存。或者,您可以在每行写入另一个文件,但吞吐量会降低。您还可以考虑将它们一起批处理到文件中。答案 1 :(得分:0)
您可以使用正则表达式轻松替换它:
replaceAll("\\w+ = ", "")
答案 2 :(得分:0)
试试这个:
修改强>
更改正则表达式以包含带空格的单词模式:
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.*;
import java.util.*;
public class YourClass {
public static void main(String[] args) {
// Path to the file being converted
String infile = "C:/Users/.../test.txt"; // Some absolute path
// Path to the destination output file
String outfile = "C:/Users/.../test.csv"; // Some absolute path
try {
// Read all rows from the infile
List<String> rows = Files.readAllLines(Paths.get(infile), Charset.forName("UTF-8"));
// List of new rows to write to the outfile
ArrayList<String> nrows = new ArrayList<String>();
// Enumerate rows
for (String row : rows) {
// Remove any word followed by any number of spaces and
// an equals sign followed by any number of spaces
String nrow = row.replaceAll("[\\w\\s]+\\s*=\\s*", "");
// Append edited row to new rows
nrows.add(nrow);
}
// Get file descriptor
Path file = Paths.get(outfile);
// Write rows to outfile
Files.write(file, nrows, Charset.forName("UTF-8"));
// Update G/TUI
System.out.println("CSV Written");
}
catch (IOException e) {
// You should catch specific exceptions
e.printStackTrace();
}
}
}