❶ java中怎樣從文件中讀取數據
分為讀位元組,讀字元兩種讀法x0dx0a◎◎◎FileInputStream 位元組輸入流讀文件◎◎◎x0dx0apublic class Maintest {x0dx0ax0dx0apublic static void main(String[] args) throws IOException {x0dx0ax0dx0aFile f=new File("G:\\just for fun\\xiangwei.txt");x0dx0ax0dx0aFileInputStream fin=new FileInputStream(f);x0dx0ax0dx0abyte[] bs=new byte[1024];x0dx0ax0dx0aint count=0;x0dx0awhile((count=fin.read(bs))>0)x0dx0a{x0dx0ax0dx0aString str=new String(bs,0,count);//反復定義新變數:每一次都 重新定義新變數,接收新讀取的滾雹數據x0dx0ax0dx0aSystem.out.println(str);//反復輸出新變數:察槐每一次都 輸出重大沒帆新定義的新變數x0dx0a}x0dx0afin.close();x0dx0a}x0dx0a}x0dx0ax0dx0a◎◎◎FileReader 字元輸入流讀文件◎◎◎x0dx0apublic class Maintest {x0dx0apublic static void main(String[] args) throws IOException {x0dx0ax0dx0aFile f=new File("H:\\just for fun\\xiangwei.txt");x0dx0ax0dx0aFileReader fre=new FileReader(f);x0dx0ax0dx0aBufferedReader bre=new BufferedReader(fre);x0dx0ax0dx0aString str="";x0dx0awhile((str=bre.readLine())!=null)//●判斷最後一行不存在,為空x0dx0a{x0dx0aSystem.out.println(str);x0dx0a}x0dx0abre.close();x0dx0a fre.close();x0dx0ax0dx0a}x0dx0ax0dx0a}
❷ JAVA怎麼從文件中把數字讀取出來並且放到一個數組中呢
我按照你的代碼:
編寫1.txt文件:
所以'a'-'0'相當於97-48=49,所以打出來的結果才是49,同理就可以得出了字元'b'、'c'、'!'、'@'、'#'減'0'後的結果了。
❸ java讀取文件中的數字並求和!!求解!
import java.io.*;
import java.util.*;
public class test {
public static void main(String[] args){
int total=0;//臨時緩存總和並賦初始值扮讓
FileInputStream fin=null;
FileOutputStream fout=null;
BufferedReader br = null;
try{
fin=new FileInputStream("in31488.txt"廳空局);//讀取文件
fout=new FileOutputStream("out31488.txt"虧衫);//創立新文件
int temp;
String[] se=null;
br = new BufferedReader(new FileReader("in31488.txt"));
String line = br.readLine();
while((line = br.readLine()) != null){
不為空則讀取一行
se = line.split(" ");
分割存入se
}
/* 循環相加數組 */
int i,j=0;
for(i=0;i<=se.length;i++){
j=Integer.parseInt(se[i]);
total+=j;
}
fout.write(total);//寫入結果
}catch(IOException e){}
finally{
try{
if(fin!=null)
fin.close();
if(fout!=null)
fout.close();
}catch (IOException e){}
}
System.out.print("總和為:"+total);
}
❹ java 按行讀取txt文件的數字
可以通過Java的IO流實現txt文本的讀取,然後用readline實現按行讀取。具體代碼如下:
packagetest;
importjava.io.BufferedReader;
importjava.io.File;
importjava.io.FileReader;
importjava.io.IOException;
importjava.util.ArrayList;
importjava.util.List;
publicclassTest{
publicstaticdouble[]writeToDat(Stringpath){
Filefile=newFile(path);
Listlist=newArrayList();
double[]nums=null;
try{
BufferedReaderbw=newBufferedReader(newFileReader(file));
Stringline=null;
//因為不知道有幾行數據,所以先存入list集合中
while((line=bw.readLine())!=null){
list.add(line);
}
bw.close();
}catch(IOExceptione){
e.printStackTrace();
}
//確定數組長度
nums=newdouble[list.size()];
for(inti=0;i<list.size();i++){
Strings=(String)list.get(i);
nums[i]=Double.parseDouble(s);
}
returnnums;
}
publicstaticvoidmain(String[]args){
Stringpath="d:/file4.txt";
double[]nums=writeToDat(path);
for(inti=0;i<nums.length;i++){
System.out.println(nums[i]);
}
}
}
❺ 如何用java讀取一個文件中的數字
代碼:
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
try {
String file = "J:\\score.txt";
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
List als = new ArrayList();
while (br.ready()) {
Score score = new Score();
String line = br.readLine();
String[] str = line.split(":");
score.setName(str[0]);
String[] sc = str[1].split(",");
for (int i = 0; i < sc.length; i++) {
score.setAllScore(score.getAllScore()
+ Double.valueOf(sc[i]).doubleValue());
}
score.setScore(score.getAllScore() / sc.length);
als.add(score);
}
br.close();
fr.close();
for (int i = 0; i < als.size() - 1; i++) {
Score max = (Score) als.get(i);
for (int j = i + 1; j < als.size(); j++) {
Score tmp = (Score) als.get(j);
if (max.getScore() < tmp.getScore()) {
max = tmp;
als.remove(j);
als.add(i, max);
}
}
}
System.out.println("姓名\t平均分");
for (int i = 0; i < als.size(); i++) {
Score tmp = (Score) als.get(i);
System.out.println(tmp.getName() + "\t" + tmp.getScore());
}
} catch (Exception e) {
}
}
}
class Score {
private String name = "";
private double allScore = 0.0;
private double score = 0.0;
public double getAllScore() {
return allScore;
}
public void setAllScore(double allScore) {
this.allScore = allScore;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
}
輸入出結果
姓名 平均分
喬丹 83.5
李尋歡 73.0
小甜甜布萊尼 67.0
劉備 61.0
❻ java中如何從文件中讀取數據
1.package txt;
2.
3.import java.io.BufferedReader;
4.import java.io.File;
5.import java.io.FileInputStream;
6.import java.io.InputStreamReader;
7.
8./**
9. * 讀取TXE數據
10. */
11.public class ReadTxtUtils {
12. public static void main(String arg[]) {
13. try {
14. String encoding = "GBK"; // 字元編碼(可解決中文亂碼問題 )
15. File file = new File("c:/aa.txt");
16. if (file.isFile() && file.exists()) {
17. InputStreamReader read = new InputStreamReader(
18. new FileInputStream(file), encoding);
19. BufferedReader bufferedReader = new BufferedReader(read);
20. String lineTXT = null;
21. while ((lineTXT = bufferedReader.readLine()) != null) {
22. System.out.println(lineTXT.toString().trim());
23. }
24. read.close();
25. }else{
26. System.out.println("找不到指定的文件!");
27. }
28. } catch (Exception e) {
29. System.out.println("讀取文件內容操作出錯");
30. e.printStackTrace();
31. }
32. }
33.}
java讀取TXT文件中的數據,每一行就是一個數,返回一個數組,代碼?
?
List list=new ArrayList();
BufferedReader br=new BufferReader(new InputStreamReader(new FileInputStream(new File("in.txt"))));
String str=null;
while((str=br.readLine())!=null)
{
list.add(new Integer(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};
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.*;
public class xx{
public static void main(String[]args){
String s;
int[][]save=new int[3][3];
try{
BufferedReader in =new BufferedReader(new FileReader("C:\\txt.txt"));
int i=0;
while((s=in.readLine())!=null){
save[i][0]=Integer.parseInt(s.substring(0,1));
save[i][1]=Integer.parseInt(s.substring(1,2));
save[i][2]=Integer.parseInt(s.substring(2,3));
i++;
}
}
catch(FileNotFoundException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++){
System.out.print(save[i][j]);
}
System.out.println();
}
}
}
或
?
BufferedReader bf=new BufferedReader(new FileReader("Your file"));
String lineContent=null;
int i = 0;
int [][] temp = new int [3][];
while((lineContent=bf.readLine())!=null){
String [] str = lineContent.split("\\d");// 將 lineContent 按數字拆分
for(int j = 0; j < str.length(); j++){
int [i][j] = Integer.parseInt(str[j]);
}
i++;
}
scp|cs|ff|201101
這是d:\\a.txt的數據,與「|」分割取數據出來,保存在變數a;b;c;d里
import java.io.*;
public class Test{
public static void main(String[] args)throws Exception{
String a, b, c, d;
StringBuffer sb = new StringBuffer();
BufferedReader br = new BufferedReader(new FileReader("d:\\a.txt"));
String s = br.readLine();
while(s != null){
sb.append(s);
s = br.readLine();
}
s = sb.toString();
String[] str = s.split("|");
a = str[0];
b = str[0];
c = str[0];
d = str[0];
}
}
❼ java從文件中讀取int整數
代碼如下:
importjava.io.BufferedReader;
importjava.io.File;
importjava.io.FileReader;
importjava.io.IOException;
importjava.util.regex.Matcher;
importjava.util.regex.Pattern;
publicclassApp{
publicstaticvoidmain(String[]args)throwsIOException{
try(FileReaderfileReader=newFileReader(newFile("OutFile.txt"));
BufferedReaderreader=newBufferedReader(fileReader);){
Stringline="";
Patternpattern=Pattern.compile("Valueat:\d+=(\d+)");
while((line=reader.readLine())!=null){
Matchermatcher=pattern.matcher(line);
if(matcher.find()){
intval=Integer.parseInt(matcher.group(1));
System.out.println(val);
}
}
}
}
}
❽ java中讀取txt文件時怎麼將數字和字元串提取出來
package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
class Test {
private static BufferedReader bw;
public static void main(String[] args) {
String ss = null;
List<TestPo> list = new ArrayList<TestPo>();
try{
File file=new File("E:\\test.txt");
FileOutputStream out=new FileOutputStream(new File("E:\\test1.txt"),true);
bw=new BufferedReader(new FileReader(file));
boolean flag = true;
int[] temps = null;
while((ss=bw.readLine())!=null){
String[] mark = ss.split(":");
int sum =0;
TestPo po = new TestPo();
int[] temp = new int[mark.length-1];
temps = new int[mark.length-1];
for (int i = 1;i< mark.length;i++) {
temp[i-1] = Integer.parseInt(mark[i].trim());
sum += temp[i-1];
if (flag) {
temps[i-1] = 0;
}
}
flag = false;
po.setMark(temp);
po.setName(mark[0]);
po.setAvg(sum/(mark.length-1));
list.add(po);
out.write(("\t\n"+ss).getBytes());
}
bw.close();
out.close();
int row = list.size();
int[][] marks = new int[row+1][];
for (int i = 0; i < row; i++) {
marks[i] = list.get(i).getMark();
}
marks[row] = temps;
int sumTemp =0 ;
int count = list.get(0).getMark().length;
for (int i = 0; i < count; i++) {
for (int j = 0; j < row; j++) {
sumTemp += marks[j][i];
}
marks[row][i] = sumTemp/row;
sumTemp = 0;
}
for (int[] is : marks) {
for (int i : is) {
System.out.print(i+" ");
}
System.out.println();
}
}catch(IOException e){
e.printStackTrace();
}
for (TestPo po : list) {
System.out.println("Name:"+po.getName()+" AVG:"+po.getAvg());
}
}
}
class TestPo{
private String name;
private Integer avg;
private int[] mark;
public int[] getMark() {
return mark;
}
public void setMark(int[] mark) {
this.mark = mark;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAvg() {
return avg;
}
public void setAvg(Integer avg) {
this.avg = avg;
}
}
❾ java中怎麼從文件中讀取數
1.package txt;
2.
3.import java.io.BufferedReader;
4.import java.io.File;
5.import java.io.FileInputStream;
6.import java.io.InputStreamReader;
7.
8./**
9. * 讀取TXE數據
10. */
11.public class ReadTxtUtils {
12. public static void main(String arg[]) {
13. try {
14. String encoding = "GBK"; // 字元編碼(可解決中文亂碼問題 )
15. File file = new File("c:/aa.txt");
16. if (file.isFile() && file.exists()) {
17. InputStreamReader read = new InputStreamReader(
18. new FileInputStream(file), encoding);
19. BufferedReader bufferedReader = new BufferedReader(read);
20. String lineTXT = null;
21. while ((lineTXT = bufferedReader.readLine()) != null) {
22. System.out.println(lineTXT.toString().trim());
23. }
24. read.close();
25. }else{
26. System.out.println("找不到指定的頌激豎文件!");
27. }
28. } catch (Exception e) {
29. System.out.println("讀取文件內容操作出錯");
30. e.printStackTrace();
31. }
32. }
33.}
java讀取鉛尺TXT文件中的數據,每一行就是一個數,返回一個數組,代碼?
?
List list=new ArrayList();
BufferedReader br=new BufferReader(new InputStreamReader(new FileInputStream(new File("in.txt"))));
String str=null;
while((str=br.readLine())!=null)
{
list.add(new Integer(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};
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.*;
public class xx{
public static void main(String[]args){
String s;
int[][]save=new int[3][3];
try{
BufferedReader in =new BufferedReader(new FileReader("C:\\txt.txt"));
int i=0;
while((s=in.readLine())!=null){
save[i][0]=Integer.parseInt(s.substring(0,1));
save[i][1]=Integer.parseInt(s.substring(1,2));
save[i][2]=Integer.parseInt(s.substring(2,3));
i++;
}
}
catch(FileNotFoundException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++){
System.out.print(save[i][j]);
}
System.out.println();
}
}
}
或
?
BufferedReader bf=new BufferedReader(new FileReader("Your file"));
String lineContent=null;
int i = 0;
int [][] temp = new int [3][];
while((lineContent=bf.readLine())!=null){
String [] str = lineContent.split("\\d");// 將 lineContent 按數字拆分
for(int j = 0; j < str.length(); j++){
int [i][j] = Integer.parseInt(str[j]);
}
i++;
}
scp|cs|ff|201101
這是d:\\a.txt的數據,與「|」分割取數據出來,保存在變數a;b;c;d里
import java.io.*;
public class Test{
public static void main(String[] args)throws Exception{
String a, b, c, d;
StringBuffer sb = new StringBuffer();
BufferedReader br = new BufferedReader(new FileReader("d:\\a.txt"));
String s = br.readLine();
while(s != null){
sb.append(s);
s = br.readLine();
}
s = sb.toString();
String[] str = s.split("|");
a = str[0];
b = str[0];
c = str[0];
d = str[0];
}
}
❿ java 怎麼讀取文件中的字元和數據
JDK版本 1.5
測試結果
result.txt 文件中的內容如下
李明 40:50:60:70:80
姓名:李明 總成績:300
劉勝 45:55:65:75:85
姓名:劉勝 總成績:625
不明白+QQ 379821283
代碼如下:
package com.rabbit.test;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class TestFile {
public static void main(String[] args) throws Exception{
//獲得文件輸入流 假設目標文件名為data.txt
FileInputStream fin = new FileInputStream("data.txt");
InputStreamReader inR = new InputStreamReader(fin);
BufferedReader bfR = new BufferedReader(inR);
//獲得文件輸出流 假設目標文件名為resutl.txt 追加方式
FileOutputStream fout = new FileOutputStream("resutl.txt",true);
OutputStreamWriter outW = new OutputStreamWriter(fout);
BufferedWriter bfW = new BufferedWriter(outW);
String temp = "";//臨時緩存 保存讀取到的每一行記錄
String[] tempArr = {};//臨時緩存 保存用空格拆分該行記錄得到的數組
String name="";//臨時緩存 保存姓名
String[] scoreTemp = {};//臨時緩存 保存分數串拆分後得到的數組
int totalScore = 0;//臨時緩存 總成績
//開始讀文件
while((temp=bfR.readLine())!=null){
//正則表達式拆分讀取到的每行 拆分成 姓名+分數串
tempArr = temp.split("[ ]+");
//得到姓名
name = tempArr[0];
//正則表達式拆分分數串得到分數數組
scoreTemp = tempArr[1].split(":");
//循環分數數組 得到總成績
for(int i=0;i<scoreTemp.length;i++){
totalScore += Integer.parseInt(scoreTemp[i]);
}
//寫入結果文件
bfW.write(temp+"\r\n");
bfW.write("姓名:"+name+" 總成績:"+totalScore+"\r\n");
}
//關閉流
bfR.close();
bfW.close();
}
}
測試正常