您的位置:首页 > 编程语言 > Java开发

JAVA中,文件的输入输出(1)

2015-10-19 21:28 429 查看
一,从文件中读取数据

package com.File1.java;

//import java.util.*;
import java.io.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile1 {
public static void main(String [] args) throws IOException
{
try
{
File f=new File("E:/test.txt");
//BufferedReader bre=new BufferedReader(new FileReader(f));
BufferedReader bre =new BufferedReader(new InputStreamReader(new FileInputStream(f)));
String str=null;
while((str=bre.readLine())!=null)
{
System.out.println(str);
}
bre.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}

}


2,从文件中读取一维数组,在txt文件中先建立例如1 2 3 4 5 6 7.

package com.File1.java;

//import java.util.*;
import java.io.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile1 {

private static int N=100;
public static void main(String [] args) throws IOException
{
try
{

double []shuzu=new double
;
int [] shuzu2=new int
;
String [] shuzu3=new String
;
File f=new File("E:/test.txt");
//@SuppressWarnings("resource")
//BufferedReader bre=new BufferedReader(new FileReader(f));
//BufferedReader bre =new BufferedReader(new InputStreamReader(new FileInputStream(f)));
BufferedReader bre =new BufferedReader(new FileReader(f));

String line;
int k=0;
while((line=bre.readLine())!=null)
{
String []temp=line.split(" ");

for(int j=0;j<temp.length;j++)
{
shuzu[j]=Double.parseDouble(temp[j]);
shuzu2[j]=Integer.parseInt(temp[j]);
shuzu3[j]=temp[j];
//System.out.print(shuzu[j]+" ");
k++;
}
}
/*
String line2;
while((line2=bre.readLine())!=null)
{
String [] temp1=line2.split(" ");  //就是读取字符串一直读取到空格位置
for(int j=0;j<temp1.length;j++)
{
shuzu2[j]=Integer.valueOf(temp1[j]);//parseInt(temp1[j]);
}
}
*/
System.out.print("转化成double型: ");

for(int i=0;i<k;i++)
{
System.out.print(shuzu[i]+"  ");
}
System.out.println();
System.out.print("转化成int型: ");
for(int m=0;m<k;m++)
{
System.out.print(shuzu2[m]+" ");
}
System.out.println();
System.out.print("转换成String型: ");
for(int n=0;n<k;n++)
{
System.out.print(shuzu3
+" ");

}
System.out.println();

//System.out.println(bre);
/*String s="";
String s1;
while((s1=bre.readLine())!=null)
{
s=s+s1;
}

String[] str=s.split("");
System.out.println(str);
int []datas=new int[str.length];

for(int j=0;j<str.length;j++)
{
datas[j]=Integer.parseInt(str[j]);
}

for(int i=0;i<datas.length;i++)
{
System.out.print(datas[i]+" ");
}

bre.close();

System.out.println();

*/
/*
String str=null;
while((str=bre.readLine())!=null)
{
System.out.println(str);
}
bre.close();

*/

}
catch(Exception e)
{
e.printStackTrace();
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: