导航:首页 > 编程语言 > java读取文件中的数组

java读取文件中的数组

发布时间:2022-07-04 15:43:53

1. java从文件中读数组

从流里面读出文件包含的长字符串,然后处理这个字符串,用split() 拆分成数组

2. java关于文件读取和数组问题

从文件格式来看,数据是以空格作为列间隔,以换行作为行间隔。

所以,

在读取数据的时候,第一行忽略,然后按照。

姓名 年龄 国家 日期 项目 金 银 铜 总数 这个顺序去读取字符。

并且转义成你要的数据结构。

读完全部行后,你就有了一个list,或者数组。


最后就是统计了。


可以参考:

package;

importjava.io.BufferedReader;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.IOException;
importjava.io.InputStreamReader;
importjava.util.ArrayList;
importjava.util.HashMap;
importjava.util.Iterator;
importjava.util.List;
importjava.util.Map;
importjava.util.StringTokenizer;

publicclassReadFile{
/**
*main方法
*
*@paramargs
*@throwsIOException
*/
publicstaticvoidmain(Stringargs[]){
Filefile=newFile("src//olympics.txt");
BufferedReaderreader=null;
try{
reader=readFile(file);
}catch(IOExceptione){
e.printStackTrace();
System.out.println("无法读取文件,可能文件不存在");
return;
}
List<Record>records=newArrayList<Record>();
try{
/**
*这里过滤第一条(行)记录
*/
Stringstr=reader.readLine();
str=reader.readLine();
for(;str!=null;str=reader.readLine()){
//System.out.println(str);
Recordrecord=wrapData(str);
if(record==null){
continue;
}else{
records.add(record);
}
}
}catch(IOExceptione){
e.printStackTrace();
System.out.println("读取文件的过程中发生了错误");
return;
}finally{
if(reader!=null){
try{
reader.close();
}catch(IOExceptione){
e.printStackTrace();
System.out.println("文件无法关闭!");
return;
}
}
}
//System.out.println(records.size());
if(records==null||records.size()==0){
System.out.println("没有任何记录");
return;
}
Map<String,Integer>map=countMedals(records);
Iterator<String>iterator=map.keySet().iterator();
while(iterator.hasNext()){
Stringkey=(String)iterator.next();
System.out.println(key+":"+map.get(key));
}
}

/**
*统计每个国家获得的奖牌数量
*
*@paramrecords
*@return
*/
publicstaticMap<String,Integer>countMedals(List<Record>records){
Map<String,Integer>map=newHashMap<String,Integer>();
for(inti=0;i<records.size();i++){
Recordrecord=records.get(i);
Integerold=map.get(record.getCountry());
if(old!=null){
map.put(record.getCountry(),old+record.getTotle());
}else{
map.put(record.getCountry(),record.getTotle());
}
}
returnmap;
}

/**
*将一条记录(String)转换成一个记录(Record)
*
*@paramstr
*@return
*/
publicstaticRecordwrapData(Stringstr){
if(str==null){
returnnull;
}
Recordrecord=null;
/**
*这里我只是用空格做分隔符,你也可以重写这段代码,使得tab或其它不可见字符也可以做分隔符。
*/
StringTokenizerst=newStringTokenizer(str,"");
//System.out.println(st.countTokens());
if(st.countTokens()==10){
record=newRecord((String)(st.nextElement()),
(String)(st.nextElement()),(String)(st.nextElement()),
(String)(st.nextElement()),(String)(st.nextElement()),
(String)(st.nextElement()),(String)(st.nextElement()),
(String)(st.nextElement()),(String)(st.nextElement()),
(String)(st.nextElement()));
returnrecord;
}
returnnull;
}

/**
*读文件
*
*@paramfile
*@return
*@throwsIOException
*/
(Filefile)throwsIOException{
BufferedReaderreader=null;
=null;
=null;
try{
fileInputStream=newFileInputStream(file);
inputStreamReader=newInputStreamReader(fileInputStream);
reader=newBufferedReader(inputStreamReader);
returnreader;
}catch(FileNotFoundExceptione){
e.printStackTrace();
//if(fileInputStream!=null){
//fileInputStream.close();
//}
//if(fileInputStream!=null){
//fileInputStream.close();
//}
//if(reader!=null){
//reader.close();
//}
throwe;
}
}
}

/**
*获奖记录的数据结构
*
*@authorAdministrator
*
*/
classRecord{
privateStringname;
privateintage;
privateStringcountry;
/*
*关于日期,这里就直接使用String了,如果你有需要,可以自己转义一下。比如使用SimpleDateFormat("yyyy/MM/dd")或(
*"yyyy")等等
*/
privateStringyear;
privateStringdate;
privateStringsport;
privateintgold;
privateintsilver;
privateintcopper;
privateinttotle;

publicRecord(Stringname,Stringage,Stringcountry,Stringyear,
Stringdate,Stringsport,Stringgold,Stringsilver,
Stringcopper,Stringtotle){
this.name=name;
this.age=Integer.valueOf(age);
this.country=country;
this.year=year;
this.date=date;
this.sport=sport;
this.gold=Integer.valueOf(gold);
this.silver=Integer.valueOf(silver);
this.copper=Integer.valueOf(copper);
this.setTotle(Integer.valueOf(totle));
}

publicRecord(){

}

publicRecord(Stringname,intage,Stringcountry,Stringyear,
Stringdate,Stringsport,intgold,intsilver,intcopper,
inttotle){
super();
this.name=name;
this.age=age;
this.country=country;
this.year=year;
this.date=date;
this.sport=sport;
this.gold=gold;
this.silver=silver;
this.copper=copper;
this.setTotle(totle);
}

publicStringgetName(){
returnname;
}

publicvoidsetName(Stringname){
this.name=name;
}

publicintgetAge(){
returnage;
}

publicvoidsetAge(intage){
this.age=age;
}

publicStringgetCountry(){
returncountry;
}

publicvoidsetCountry(Stringcountry){
this.country=country;
}

publicStringgetDate(){
returndate;
}

publicvoidsetDate(Stringdate){
this.date=date;
}

publicStringgetSport(){
returnsport;
}

publicvoidsetSport(Stringsport){
this.sport=sport;
}

publicintgetGold(){
returngold;
}

publicvoidsetGold(intgold){
this.gold=gold;
}

publicintgetSilver(){
returnsilver;
}

publicvoidsetSilver(intsilver){
this.silver=silver;
}

publicintgetCopper(){
returncopper;
}

publicvoidsetCopper(intcopper){
this.copper=copper;
}

publicintgetTotle(){
returntotle;
}

publicvoidsetTotle(inttotle){
this.totle=totle;
}

publicStringgetYear(){
returnyear;
}

publicvoidsetYear(Stringyear){
this.year=year;
}

}

文件:因为读文件对格式的要求很高,所以这里将中间空白部分全部替换成了空格,你也可以在代码中做判断,如果是tab或者其它空白字符也可以做分隔符。
姓名年龄国家年日期项目金银铜总数
/12/2012Taekwondo0011
/24/2008Taekwondo0011
AmarBenikhlef26Algeria20088/24/2008Judo0101
SorayaHaddad23Algeria20088/24/2008Judo0011
MohamedAllalou26Algeria200010/1/2000Boxing0011
/12/2012Athletics1001

结果:
Afghanistan:2
Algeria:4

想起以前在学校的时候做过C语言版本的类似东西,这里我就帮你写一个Java版本的吧。采用了面向对象的设计,很多代码已经抽取出来了。
没怎么做过测试。代码的健壮性你自己慢慢搞吧。关键是文件的格式一定不能错。当然你也可以在代码中对文件格式增加包容。

3. JAVA读取文件内容并放入数组

{/***以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。*/(StringfileName){Filefile=newFile(fileName);InputStreamin=null;try{System.out.println("以字节为单位读取文件内容,一次读一个字节:");//一次读一个字节in=newFileInputStream(file);inttempbyte;while((tempbyte=in.read())!=-1){System.out.write(tempbyte);}in.close();}catch(IOExceptione){e.printStackTrace();return;}try{System.out.println("以字节为单位读取文件内容,一次读多个字节:");//一次读多个字节byte[]tempbytes=newbyte[100];intbyteread=0;in=newFileInputStream(fileName);ReadFromFile.showAvailableBytes(in);//读入多个字节到字节数组中,byteread为一次读入的字节数while((byteread=in.read(tempbytes))!=-1){System.out.write(tempbytes,0,byteread);}}catch(Exceptione1){e1.printStackTrace();}finally{if(in!=null){try{in.close();}catch(IOExceptione1){}}}}/***以字符为单位读取文件,常用于读文本,数字等类型的文件*/(StringfileName){Filefile=newFile(fileName);Readerreader=null;try{System.out.println("以字符为单位读取文件内容,一次读一个字节:");//一次读一个字符reader=newInputStreamReader(newFileInputStream(file));inttempchar;while((tempchar=reader.read())!=-1){//对于windows下,
这两个字符在一起时,表示一个换行。//但如果这两个字符分开显示时,会换两次行。//因此,屏蔽掉
,或者屏蔽
。否则,将会多出很多空行。if(((char)tempchar)!='
'){System.out.print((char)tempchar);}}reader.close();}catch(Exceptione){e.printStackTrace();}try{System.out.println("以字符为单位读取文件内容,一次读多个字节:");//一次读多个字符char[]tempchars=newchar[30];intcharread=0;reader=newInputStreamReader(newFileInputStream(fileName));//读入多个字符到字符数组中,charread为一次读取字符数while((charread=reader.read(tempchars))!=-1){//同样屏蔽掉
不显示if((charread==tempchars.length)&&(tempchars[tempchars.length-1]!='
')){System.out.print(tempchars);}else{for(inti=0;i<charread;i++){if(tempchars[i]=='
'){continue;}else{System.out.print(tempchars[i]);}}}}}catch(Exceptione1){e1.printStackTrace();}finally{if(reader!=null){try{reader.close();}catch(IOExceptione1){}}}}/***以行为单位读取文件,常用于读面向行的格式化文件*/(StringfileName){Filefile=newFile(fileName);BufferedReaderreader=null;try{System.out.println("以行为单位读取文件内容,一次读一整行:");reader=newBufferedReader(newFileReader(file));StringtempString=null;intline=1;//一次读入一行,直到读入null为文件结束while((tempString=reader.readLine())!=null){//显示行号System.out.println("line"+line+":"+tempString);line++;}reader.close();}catch(IOExceptione){e.printStackTrace();}finally{if(reader!=null){try{reader.close();}catch(IOExceptione1){}}}}/***随机读取文件内容*/(StringfileName){RandomAccessFilerandomFile=null;try{System.out.println("随机读取一段文件内容:");//打开一个随机访问文件流,按只读方式randomFile=newRandomAccessFile(fileName,"r");//文件长度,字节数longfileLength=randomFile.length();//读文件的起始位置intbeginIndex=(fileLength>4)?4:0;//将读文件的开始位置移到beginIndex位置。randomFile.seek(beginIndex);byte[]bytes=newbyte[10];intbyteread=0;//一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。//将一次读取的字节数赋给bytereadwhile((byteread=randomFile.read(bytes))!=-1){System.out.write(bytes,0,byteread);}}catch(IOExceptione){e.printStackTrace();}finally{if(randomFile!=null){try{randomFile.close();}catch(IOExceptione1){}}}}/***显示输入流中还剩的字节数*/(InputStreamin){try{System.out.println("当前字节输入流中的字节数为:"+in.available());}catch(IOExceptione){e.printStackTrace();}}publicstaticvoidmain(String[]args){StringfileName="C:/temp/newTemp.txt";ReadFromFile.readFileByBytes(fileName);ReadFromFile.readFileByChars(fileName);ReadFromFile.readFileByLines(fileName);ReadFromFile.readFileByRandomAccess(fileName);}}

4. Java语言怎么打开文件上的一个数组并且作为键盘的输出的结果参与运算呢

package test;

import java.io.BufferedReader;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.util.Arrays;

import java.util.Scanner;

public class Test5 {

public static void main(String[] args) throws IOException {

String path = "D:\aa.txt";//文件位置

File file = new File(path);

try {//读取文件内容

InputStream in = new FileInputStream(file);

InputStreamReader reader = new InputStreamReader(in);

BufferedReader br = new BufferedReader(reader);

String line = null;

while( (line=br.readLine()) != null){

//如果是数组则读出数据

if('['==line.charAt(0) && ']'==line.charAt(line.length()-1)){

//将读出的字符串转成数组

line = line.substring(1);

line = line.substring(0,line.length()-1);

String[] array = line.split(",");

//不知道你要怎么运算,目前就给数组中的每个数字加上用户输入的字符

System.out.print("从文件中读出的数组:");

System.out.println(Arrays.toString(array));

System.out.println("请输入加上的字符/字符串:");

Scanner sc = new Scanner(System.in);

String userStr = sc.nextLine();

//加上用户输入的数据

for(int i=0;i<array.length;i++){

array[i] += userStr;

}

System.out.print("修改后的数组:");

System.out.println(Arrays.toString(array));

}

}

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

}

5. 用java从文件中读取二维数组

纠正下,文件中是没有二维数组的概念的,也就是说必须将文件中的内容转换为二维数组中的内容。
可以通过BufferedReader 流的形式进行流缓存,之后通过readLine方法获取到缓存的内容。
BufferedReader bre = null;
try {
String file = "D:/test/test.txt";
bre = new BufferedReader(new FileReader(file));//此时获取到的bre就是整个文件的缓存流
while ((str = bre.readLine())!= null) // 判断最后一行不存在,为空结束循环
{
System.out.println(str);//此处将读取到的内容根据需要的规则,写入到二维数组中即可
};
备注: 流用完之后必须close掉,如上面的就应该是:bre.close(),否则bre流会一直存在,直到程序运行结束。

6. Java从文件中读取数据存入一个数组中

// 直接给一个只读一行的吧,呵呵,数字之间以空格来分隔public static void main(String[] args) throws Exception {File file = new File("src/test.txt");double[] a = getLineFromTxt(file," ");for(int i = 0; i< a.length; i++){System.out.println("a["+i+"] = "+a[i]);}} test中的数据以空格隔开 12 32 32.02 public static double[] getLineFromTxt(File file, String split) throws Exception{BufferedReader br = new BufferedReader(new FileReader(file));String firstLine = br.readLine(); //就读第一行哦String[] arrs = firstLine.split(" ");//将字符数组转为double数组double[] arr = new double[arrs.length];for(int i = 0; i< arr.length; i++){arr[i] = Double.parseDouble(arrs[i]);}if(br!= null){br.close();br = null;}return arr;}

7. java读取txt文件写入数组

参考代码如下:

publicclassFileReaderForRead
{
publicstaticvoidmain(String[]args)
{

try{
System.out.println(System.in);

FileReaderfileReader=newFileReader("D:\import_users.txt");
BufferedReaderbuf=newBufferedReader(fileReader);

inti=0;
StringbufToString="";
StringreadLine="";
String[]myArray=newString[500];//100:这个值你自己定义,但不宜过大,要根据你文件的大小了,或者文件的行数
while((readLine=buf.readLine())!=null){
myArray[i]=readLine;
i++;
}
}
catch(Exceptione){
e.printStackTrace();
}
}
}

8. java 以数组形式读取文件

public class Untitled1 {
public static void main(String[] args) {
try {
BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream("写上文件的路径")));
String str=br.readLine();//从文件里面读出一行
String result="";//定义你需要的字符串数组组成的字符串
while(str!=null){
result+=str;//每读一行就加到result里面去
str=br.readLine();//继续从文件里面读,知道str为空为止
}
String[] array=result.split(",");//讲得到的result按照,分开得到一个数组
for(int i=0;i<array.length;i++){
array[i]=array[i].trim();//去掉有可能读出来的空格
System.out.println("array["+i+"]==>"+array[i]);
}
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

9. java 读取txt文件得出数组,希望高手帮我补完却掉的部分并解释一下 如果是单词的呢

import java.util.*;
import java.io.*;

public class order {
public static void main(String[] args) throws IOException {
/***
* 代码填充部分
*/
//文件读取
String line2StrVal = ""; // 第二行
String line3StrVal = ""; // 第三行
int lineIndex = 1; //行索引

//创建连接
BufferedReader reader = new BufferedReader(new FileReader("d:/xiaod.txt"));
String readLine = null; //每行临时存储
//开始读取数据
while((readLine = reader.readLine()) != null){
if(lineIndex == 2){
line2StrVal = readLine;
}else if(lineIndex == 3){
line3StrVal = readLine;
}
lineIndex++;
}
reader.close(); // 关闭资源

//查看读取数据
System.out.println(line2StrVal);
System.out.println(line3StrVal);

//开始将读取数据加载到数组中
String[] arrayVal = line2StrVal.split(" ");
int a[] = new int[line2StrVal.split(" ").length];
for(int i=0;i<arrayVal.length;i++){
a[i]= Integer.parseInt(arrayVal[i]);
}
arrayVal = line3StrVal.split(" ");
double b[] = new double[line3StrVal.split(" ").length];
for(int i=0;i<arrayVal.length;i++){
b[i]= Double.parseDouble(arrayVal[i]);
}

/**
* 代码填充结束
*/
double array[] = new double[1];
for (int i = 0; i < array.length; i++) {
array[i] = a[i] * b[i];
System.out.print("Total Number of Items:");
System.out.println(a[0] + a[1] + a[2] + a[3] + a[4] + a[5]);
System.out.print("Final Cost:$ ");
System.out.println(a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3] + a[4] * b[4] + a[5] * b[5]);

}
}
}

10. Java读取TXT文件数据到数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Arrays;

public class FileToAry {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new FileReader("c:\\test.txt"));//使用BufferedReader 最大好处是可以按行读取,每次读取一行
int n = 0;//定义n
int m = 0;//定义m
int[] U = null;//定义数组
int[] S = null;//定义数组
int index = 0;//索引
String temp;//定义字符串,用于保存每行读取到的数据
while ((temp = br.readLine()) != null) {
int[] ary = aryChange(temp);//通过函数吧字符串数组解析成整数数组
if (index == 0) {
n = ary[0];
m = ary[1];
}
if (index == 1) {
U = ary;
}
if (index == 2) {
S = ary;
}
index++;
}

br.close();// 关闭输入流

// 测试输出
System.out.println("n=" + n + "\tm=" + m + "\n数组U=" + Arrays.toString(U) + "\n数组S=" + Arrays.toString(S));
}

static int[] aryChange(String temp) {// 字符串数组解析成int数组
String[] ss = temp.trim().split("\\s+");// .trim()可以去掉首尾多余的空格
// .split("\\s+")
// 表示用正则表达式去匹配切割,\\s+表示匹配一个或者以上的空白符
int[] ary = new int[ss.length];
for (int i = 0; i < ary.length; i++) {
ary[i] = Integer.parseInt(ss[i]);// 解析数组的每一个元素
}
return ary;// 返回一个int数组
}

阅读全文

与java读取文件中的数组相关的资料

热点内容
圆命令画法 浏览:303
如果给电脑e盘文件加密 浏览:799
javaswing项目 浏览:773
androidsdksetup 浏览:1001
pdf怎么设置中文 浏览:124
安卓手机用什么软件看伦敦金 浏览:962
魅族文件夹无名称 浏览:787
苏黎世无人机算法 浏览:872
核桃编程和小码王的融资 浏览:681
微积分教材pdf 浏览:723
写python给微信好友发消息 浏览:336
蚊帐自营米加密 浏览:418
学校推荐核桃编程 浏览:802
湖南农信app怎么导明细 浏览:471
福特abs编程 浏览:506
如何自学安卓手机 浏览:437
以太坊源码共识机制 浏览:910
单片机探测器 浏览:870
demo编程大赛作品怎么运行 浏览:51
学历提升用什么手机软件App 浏览:938