java文本分割并存入数组

格式:
文件名.txt 关键字/词性/权重/出现个数#关键字/词性/权重/出现个数#
文件名.txt 关键字/词性/权重/出现个数#关键字/词性/权重/出现个数#
文件名.txt 关键字/词性/权重/出现个数#关键字/词性/权重/出现个数#

把这个保存到一个类里面,类:int txtID; String txtName; double wWeight; int wCount;

第1个回答  推荐于2016-10-09

以下代码仅供参考

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

Ant[] ants;

public Main() {
ants = new Ant[100];
}

public static void main(String[] args) {
File f = new File("D:\\123.txt");
Main main = new Main();
main.decodeFile(f);

for (int i = 0, k = main.ants.length; i < k; i++) {
System.out.println(main.ants[i]);
}

}

public boolean decodeFile(File f) {
BufferedReader br;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
String lineString = "";

int txtNameIndex;
Ant ant;
String[] antString;
String txtName;
String[] childString;
int index = 0;
while ((lineString = br.readLine()) != null && index < 100) {
antString = lineString.split("#");

ant = new Ant();
txtNameIndex = antString[0].indexOf(" ");
txtName = antString[0].substring(0, txtNameIndex);

antString[0] = antString[0].substring(txtNameIndex + 1);

for (int i = 0, k = antString.length; i < k; i++) {
ant = new Ant();
childString = antString[i].split("/");
ant.txtID = index + 1;
ant.txtName = txtName;
ant.keyword = childString[0];
ant.style = childString[1];
ant.wWeight = Double.parseDouble(childString[2]);
ant.wCount = Integer.parseInt(childString[3]);
ants[index] = ant;
index++;
}

}

br.close();

} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}

}

class Ant {
int txtID;
String txtName;
String keyword;
String style;
double wWeight;
int wCount;

@Override
public String toString() {
return "[txtID:" + txtID + ",txtName:" + txtName + ",keyword:" + keyword + ",style:" + style + ",wWeight:"
+ wWeight + ",wCount:" + wCount + "]";
}
}

本回答被提问者和网友采纳
第2个回答  2015-10-19
把所有的字符看做一个字符串,以#截取,保存到数组1中,再遍历数组1,以/截取,再保存到子数组
private static String string = "文件名.txt 关键字/词性/权重/出现个数#关键字/词性/权重/出现个数#文件名.txt 关键字/词性/权重/出现个数#关键字/词性/权重/出现个数#文件名.txt 关键字/词性/权重/出现个数#关键字/词性/权重/出现个数#";
public static void main(String[] args) {
String[] strings = string.split("#");
for (int i = 0; i < strings.length; i++) {
String[] strings2 = strings[i].split("/");
for (int j = 0; j < strings2.length; j++) {
//在这里做保存的操作
System.out.print(strings2[j] + " ");
}
}
}
第3个回答  2015-10-19
很乱,不分行、找不到行的分隔,,,,,,,,追问

这个是有分行的,只是每一行太长了。我把前面的文件名删掉给你看:

一行代表一个文本的关键字。每个关键字中间用#分割。关键字/词性/权重/出现数量#                  我现在要把这个10行数据读到数组里面去。数组对应着ID KEYWORD STYLE WEIGHT COUNT.

相似回答