Java学习——读写txt文件

时间:2021-06-19 19:44:22
package HHH;
import java.io.*;
import static java.lang.System.out; public class OpenFile { public static void main(String[] args) {
// TODO Auto-generated method stub try{
FileInputStream rf = new FileInputStream("openFile.txt");
FileOutputStream wf = new FileOutputStream("write.txt");
int n=512;
byte buffer[] = new byte[n];//buffer就是个byte类型数组
while((rf.read(buffer,0,n) != -1) && (n>0))//读取输入流
{
out.print(new String(buffer));//在屏幕中输出,强制转换成字符串
wf.write(buffer,0,buffer.length); }
out.println();
rf.close();
wf.close();
}catch(IOException ioe){
out.println(ioe);
}catch(Exception e){
out.println(e);
}
} }

Java学习——读写txt文件

package HHH;

import java.util.*;
import java.io.*; public class ScannerTest2 { public static void main(String[] args) throws IOException
{
// TODO Auto-generated method stub
double sum = 0.0;
int count = 0;
FileWriter fout = new FileWriter("text.txt");
fout.write("2 2.2 3 3.3 4 4.5 done");
fout.close(); FileReader fin = new FileReader("text.txt"); Scanner in = new Scanner(fin);
while(in.hasNext())
{
if(in.hasNextDouble())
{
System.out.println(in.nextDouble());
sum = sum + in.nextDouble();
count++;
}
else
{
String str = in.next();
System.out.println(str);
if(str.equals("done"))
{
break;
}
else
{
System.out.println("文件格式错误");
return ;
}
}
}
fin.close();
System.out.println("文件中数据的平均数是:"+ sum / count); }
}

Java学习——读写txt文件