我有一个文本文件 data.txt 是如下内容的,其中“//”与字符串之间为两个空格,每行数字与字符串之间为一个 tab 分隔。
现在怎样读取文本内容?? 并将读取的数据分别写入三个 String[][2] 数组? 每个数组名为“//”后的字符串。
例如String[][] GetDta = {{"0","xixi"},{"456","download xixi"},{"45","ok, wait 7s"}} ;其他类似。
本人java初学者,请各位大侠指教!!// ErrorCorrect
1 download data
234 compute AB
33 transfer single
150 connect web
12 stop ErrorCorrect// TransferData
0 ready socket
234 parseDouble data
34 transfer, wait
53 using 10s// GetData
0 xixi
456 download xixi
45 ok, wait 7s
现在怎样读取文本内容?? 并将读取的数据分别写入三个 String[][2] 数组? 每个数组名为“//”后的字符串。
例如String[][] GetDta = {{"0","xixi"},{"456","download xixi"},{"45","ok, wait 7s"}} ;其他类似。
本人java初学者,请各位大侠指教!!// ErrorCorrect
1 download data
234 compute AB
33 transfer single
150 connect web
12 stop ErrorCorrect// TransferData
0 ready socket
234 parseDouble data
34 transfer, wait
53 using 10s// GetData
0 xixi
456 download xixi
45 ok, wait 7s
读取很简单,以 // 开头的就直接取后面的字符串;剩下的如果不是空行,用第一个空格分隔就行了。
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;public class Temp
{
public static void main(String[] args)
{
List<String> data = getFileData("F://data.txt");
List<String[]> errorCorrectList = new ArrayList<String[]>();
List<String[]> transferDataList = new ArrayList<String[]>();
List<String[]> getDataList = new ArrayList<String[]>();
String[][] errorCorrect, transferData, getData;
String name = "";
for(String str: data)
{
if(str.trim().equals(""))
{
continue;
}
if(str.startsWith("//"))
{
name = str.split(" ")[1];
continue;
}
//这里没有用equals的原因是防止受到行尾空格的干扰
if(name.indexOf("ErrorCorrect") >= 0)
{
errorCorrectList.add(str.split("\t"));
}
else if(name.indexOf("TransferData") >= 0)
{
transferDataList.add(str.split("\t"));
}
else if(name.indexOf("GetData") >= 0)
{
getDataList.add(str.split("\t"));
}
}
errorCorrect = new String[errorCorrectList.size()][2];
transferData = new String[transferDataList.size()][2];
getData = new String[getDataList.size()][2];
int index = 0;
for(String[] strs: errorCorrectList)
{
errorCorrect[index++] = strs;
}
index = 0;
for(String[] strs: transferDataList)
{
transferData[index++] = strs;
}
index = 0;
for(String[] strs: getDataList)
{
getData[index++] = strs;
}
//以下是测试代码
for(String[] strs: errorCorrect)
{
System.out.println(strs[0] + "-----" + strs[1]);
}
System.out.println();
for(String[] strs: transferData)
{
System.out.println(strs[0] + "-----" + strs[1]);
}
System.out.println();
for(String[] strs: getData)
{
System.out.println(strs[0] + "-----" + strs[1]);
}
}
/**
* 从文件读取数据
* @param path 文件路径
* @return 文件数据
*/
public static List<String> getFileData(String path)
{
List<String> result = new ArrayList<String>();
FileReader fr = null;
BufferedReader br = null; try
{
fr = new FileReader(path);
br = new BufferedReader(fr);
String str; while((str = br.readLine()) != null)
{
result.add(str);
}
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if(fr != null)
{
fr.close();
} if(br != null)
{
br.close();
}
}
catch(IOException e)
{
e.printStackTrace();
}
} return result;
}
}
另外,在文本中搜索标志,再读取标志处文本是用indexOf(String str)吧??
用Map <String, String[][]> 实现的方法具体怎样做??方便的话能大概给出代码示例不??
我也想参考下!!
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;/**
* see:
* http://topic.csdn.net/u/20090327/13/c66cdb00-124b-48a7-89b7-e6e1436adc1f.html
*
* @author hyd
*/
public class FileReader { private static final String FILE_NAME = "/home/hyd/workspace/MyTools/demodata"; // 程序入口
public static void main(String[] args) throws Exception {
Storage store = new Storage();
FileLineIterator it = new FileLineIterator(FILE_NAME); // 读取并解析
while (it.hasNextLine()) {
store.parseLine(it.getLine());
} it.close(); // 输出结果
System.out.println(store);
} // 读取文件的类
private static class FileLineIterator {
private BufferedReader reader; private String line; /**
* 构造方法
*
* @param filename 文件名
*
* @throws IOException 如果读取文件失败
*/
public FileLineIterator(String filename) throws IOException {
this.reader = new BufferedReader(new InputStreamReader(
new FileInputStream(filename)));
} public void close() throws IOException {
reader.close();
} public boolean hasNextLine() throws IOException {
this.line = this.reader.readLine();
return line != null;
} public String getLine() {
return line;
} } // 保存文件信息的类
private static class Storage { // 注释行的行首标记
private static final String REMARK_PREFIX = "//"; // 数字与文本的间隔符
private static final String SEPATATOR = "\t"; private Map<String, String[][]> blocks = new HashMap<String, String[][]>(); private String currentTitle; private List<String[]> currentBlock = new ArrayList<String[]>(); // 解析行
public void parseLine(String line) {
if (line.startsWith(REMARK_PREFIX)) { // 起始行
createNewBlock(line);
} else if (line.trim().length() > 0) { // 数据行
addBlockElement(line);
saveCurrentBlock();
}
// 空行被忽略
} private void addBlockElement(String line) {
int pos = line.indexOf(SEPATATOR);
String num = line.substring(0, pos);
String text = line.substring(pos + 1); currentBlock.add(new String[] { num, text });
} private void createNewBlock(String line) {
this.currentTitle = line.substring(2).trim();
blocks.put(this.currentTitle, parseBlock(this.currentBlock));
this.currentBlock = new ArrayList<String[]>();
} private void saveCurrentBlock() {
blocks.put(currentTitle, parseBlock(currentBlock));
} private String[][] parseBlock(List<String[]> block) {
String[][] result = new String[block.size()][];
for (int i = 0; i < block.size(); i++) {
result[i] = block.get(i);
}
return result;
} public String toString() {
StringBuffer sb = new StringBuffer(""); for (String title : blocks.keySet()) {
sb.append(title).append(":\n");
for (String[] strs : blocks.get(title)) {
sb.append("{\"").append(strs[0]).append("\",\"").append(
strs[1]).append("\"}\n");
}
sb.append("\n");
}
return sb.toString();
}
}
}运行之前将 FILE_NAME 改成实际的文件路径。