java如何从txt文件中读取数据
2.
3 .导入Java . io . buffered reader;
4 .导入Java . io . file;
5 .导入Java . io . file inputstream;
6 .导入Java . io . inputstreamreader;
7.
8./**
9.*读取TXE数据
10.*/
11 . public class ReadTxtUtils {
12.公共静态void main(String arg[]) {
13.尝试{
14.string encoding = " GBK ";//字符编码(可以解决中文乱码问题)
15.File File = new File(" c:/aa . txt ");
16.if(file . is file()& amp;& ampfile.exists()) {
17.InputStreamReader read = new InputStreamReader(
18.new FileInputStream(文件),编码);
19.buffered reader buffered reader = new buffered reader(read);
20.String lineTXT = null
21.while((line txt = buffered reader . readline())!= null) {
22.system . out . println(line txt . tostring()。trim());
23.}
24.read . close();
25.}否则{
26.System.out.println("找不到指定的文件!");
27.}
28.} catch(异常e) {
29.System.out.println("读取文件内容出错");
30.e . printstacktrace();
31.}
32.}
33.}
Java读取TXT文件中的数据,每行是一个数字,返回一个数组,代码?
list list = new ArrayList();
buffered reader br = new buffer reader(new InputStreamReader(new File inputstream(new File(" in . txt "))));
String str = null
while((str=br.readLine())!=空)
{
list.add(新整数(str));
}
Integer[]I = new Integer[list . size()];
list . toarray(I);
在TXT文本中,内容如下:
123
456
789
读取二维数组的效果是:
temp[0][]={1,2,3 };
temp[1][]={4,5,6 };
temp[2][]={7,8,9 };
导入Java . io . buffered reader;
import Java . io . filenotfoundexception;
导入Java . io . filereader;
导入Java . io . *;
公共类xx{
公共静态void main(String[]args){
字符串s;
int[][]save = new int[3][3];
尝试{
buffered reader in = new buffered reader(new FileReader(" C:\ \ txt . txt "));
int I = 0;
while((s=in.readLine())!=null){
save[I][0]= integer . parse int(s . substring(0,1));
save[I][1]= integer . parse int(s . substring(1,2));
save[I][2]= integer . parse int(s . substring(2,3));
i++;
}
}
catch(FileNotFoundException e){
e . printstacktrace();
}
catch(IOException e){
e . printstacktrace();
}
for(int I = 0;我& lt3;i++)
{
for(int j = 0;j & lt3;j++){
System.out.print(保存[I][j]);
}
system . out . println();
}
}
}
或者
buffered reader BF = new buffered reader(new file reader("你的文件"));
String lineContent = null
int I = 0;
int[][]temp = new int[3][];
while((lineContent=bf.readLine())!=null){
string[]str = line content . split(" \ \ d ");//按数字拆分lineContent
for(int j = 0;j & ltstr . length();j++){
int[I][j]= integer . parse int(str[j]);
}
i++;
}
scp | cs | ff | 201101
这是d:\\a.txt的数据,从“|”中分离出来得到数据,存储在变量a中;b;c;李
导入Java . io . *;
公共类测试{
公共静态void main(String[] args)引发异常{
字符串a、b、c、d;
string buffer sb = new string buffer();
buffered reader br = new buffered reader(new FileReader(" d:\ \ a . txt "));
string s = br . readline();
while(s!= null){
某人追加;
s = br . readline();
}
s = sb . tostring();
string[]str = s . split(" | ");
a = str[0];
b = str[0];
c = str[0];
d = str[0];
}
}