JAVA如何从文本文档每行中读取需要的内容到数组中?

2024-11-06 05:39:01
推荐回答(3个)
回答(1):

调试了一个 把上面的东西方到f盘下ip.txt中 运行我的代码就可以了
import java.io.*;
public class ReadFileIP {
public static void main(String[] args) {
String[] stringArgs = new String[50];
File file = new File("F:\\ip.txt");
FileReader fr;
String str = null;
try {
fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
int i = 0;
while ((str = br.readLine()) != null) {
str = str.trim();
if (-1 != (str.lastIndexOf("ms"))) {
stringArgs[i] = str.substring(str.lastIndexOf("ms") + 2);
i++;
System.out.println(stringArgs[i - 1]);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

回答(2):

//用到的类
TextReader:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class TextReader {

private BufferedReader breader = null;

private FileReader freader = null;

public TextReader(File file) {
init(file);
}

public BufferedReader getBufreredReader() {
return breader;
}

private void init(File file) {

try {
freader = new FileReader(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (freader != null) {
breader = new BufferedReader(freader);
}

}

public String readAll() {
StringBuffer result = new StringBuffer("");
String temp;
while ((temp = readLine()) != null) {
result.append(temp + "\n");
}
return result.toString();

}

public String readLine() {

String line = null;
try {
line = breader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return line;
}

public void close() {

if (breader != null) {
try {
breader.close();
} catch (IOException e) {
e.printStackTrace();
}
} else if (freader != null) {
try {
freader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

}
//这里匹配,存到ArrayList里了,可以转化为String数组的

import java.io.File;
import java.util.ArrayList;
import java.util.regex.*;

public class Pri{

public static void main(String args[]){
String ipRegex = "(((\\d{1})|(\\d{2})" +
"|(1\\d{2})|(2[0-4]\\d{1})|" +
"(25[0-5]))\\.){3}((\\d{1})|" +
"(\\d{2})|(1\\d{2})|(2[0-4]\\d{1})" +
"|(25[0-5]))";
Pattern p = Pattern.compile(ipRegex);
TextReader tr = new TextReader(new File("F:\\jtest\\ip.txt"));
String con = tr.readAll();
Matcher m = p.matcher(con);
ArrayList list = new ArrayList();
while(m.find()) {
list.add(m.group());
}
Object [] ips = list.toArray();
for(int i = 0; i < ips.length; i ++) {
System.out.println(ips[i]);
}
}
}

回答(3):

用正则表达式
具体怎么用我忘了
你可以去查下