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數組
}