❶ 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();
}
}
测试正常