我有一个文本文件,上面写着
18 8 307 130 3504 12 70 1 10
15 8 350 165 3693 11 70 1 10
18 8 318 150 3436 11 70 1 10
16 8 304 150 3433 12 70 1 10
17 8 302 140 3449 10 70 1 10其中每个值由单个空格分隔。有没有什么算法可以让我们只选择特定的列,而不是所有的列,并将它们写到另一个文件中?
对于ex。我想在第一列,第二列,第五列和第六列工作,所以我的代码应该选择这些列中的所有属性,并在另一个文件中重写它们。
发布于 2014-03-11 14:13:27
算法可以是这样的。
1-First calculate number of rows and columns exists in file by any method.
int col,row;
2-Create a two dimensional matrix
int matrix[row][col]
and copy all elements from file to matrix.
3-Now you have the matrix you can access any column of your choice and can perform any operation in this.这可以更精致,但想法应该是这样的。
发布于 2014-03-11 14:19:08
答案:
static final String s = "18 8 307 130 3504 12 70 1 10 \n" +
"15 8 350 165 3693 11 70 1 10 \n" +
"18 8 318 150 3436 11 70 1 10 \n" +
"16 8 304 150 3433 12 70 1 10 \n" +
"17 8 302 140 3449 10 70 1 10";
public static void main(String... str) {
List<String> lines = Arrays.asList(s.split("\\n"));
StringBuilder sb = new StringBuilder();
for (String s : lines) {
String[] tempStr = s.split("\\s");
appendRightColumns(sb, tempStr);
}
writeToFile(sb);
}
private static void writeToFile(StringBuilder sb) {
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter("C:\\your_file.txt"));
writer.write(sb.toString());
} catch (IOException e) {
} finally {
try {
if (writer != null)
writer.close();
} catch (IOException e) {
}
}
}
private static void appendRightColumns(StringBuilder sb, String[] tempStr) {
sb.append(tempStr[0]);
sb.append(" ");
sb.append(tempStr[1]);
sb.append(" ");
sb.append(tempStr[4]);
sb.append(" ");
sb.append(tempStr[5]);
sb.append("\n");
}发布于 2014-03-11 14:56:17
请尝试以下操作:
public void read() throws FileNotFoundException, IOException
{
FileInputStream fstream = new FileInputStream("screendump");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
processLine(strLine );
}
}
protected void processLine(String aLine){
//use a second Scanner to parse the content of each line
Scanner scanner = new Scanner(aLine);
if (scanner.hasNext()){
//assumes the line has a certain structure
switch(i)
{
case 1:
//store in string id = scanner.next().trim();
break;
case 2:
//store in string id+ = scanner.next().trim();
break;
case 3:
break;
case 4:
break;
case 5:
//store in string id+ = scanner.next().trim();
break;
case 6:
//store in string id+ = scanner.next().trim();
break;
default:
break;https://stackoverflow.com/questions/22317653
复制相似问题