java边读边写代码 java写代码技巧

java读写同一个文件

读取文件有三种方式,r, w, a,读,覆盖写, 追加写, new FileReader(file)以读的方式打开了文件,两个马上就以new FileWriter(file)方式覆盖写文件,文件自然是空白的,之后你readLine读到的是null,即String line是null,然后你要writer.write(line); 即writer.write(null); 自然报空指针;

创新互联公司服务项目包括烈山网站建设、烈山网站制作、烈山网页制作以及烈山网络营销策划等。多年来,我们专注于互联网行业,利用自身积累的技术优势、行业经验、深度合作伙伴关系等,向广大中小型企业、政府机构等提供互联网行业的解决方案,烈山网站推广取得了明显的社会效益与经济效益。目前,我们服务的客户以成都为中心已经辐射到烈山省份的部分城市,未来相信会继续扩大服务区域并继续获得客户的支持与信任!

建议,如果边读边写,考虑RandomAccessFile类

java如何实现对同一个text文本边写边读

import java.io.*;

import java.lang.*;

import java.util.Scanner;

import java.io.*;

import java.lang.*;

public class Sy2Student

{

public static void main(String []args)

{

Writer Swriter=null;

Scanner s=new Scanner(System.in);

System.out.print("输入学生的人数:");

int Studentpeople=s.nextInt();

String []StudentScore=new String[Studentpeople];

String []StudentName=new String[Studentpeople];

System.out.println("请输入学生的姓名和总分");

for(int i=0;iStudentpeople;i++)

{

StudentName[i]=s.next();

StudentScore[i]=s.next();

System.out.println("\n");

}

int []IntStudentScore=new int[Studentpeople];

for(int n=0;nStudentpeople;n++)

{

IntStudentScore[n]=Integer.parseInt(StudentScore[n]);

}

int StudentScoreMin=IntStudentScore[0];

int StudentScoreMax=IntStudentScore[0];

for(int m=1;mStudentpeople;m++)

{

int AllScore=IntStudentScore[0];

AllScore+=IntStudentScore[m];

//求最低分

if(StudentScoreMinIntStudentScore[m])

StudentScoreMin=IntStudentScore[m];

else

StudentScoreMin=StudentScoreMin;

}

//求最高分

for(int p=0;pStudentpeople;p++)

{

if(StudentScoreMaxIntStudentScore[p])

StudentScoreMax=IntStudentScore[p];

else

StudentScoreMax=StudentScoreMax;

}

try{

Swriter=new FileWriter("Student.txt");

Swriter.write("学生成绩表单\n");

Swriter.write("姓名:\t\t总分:\n");

for(int j=0;jStudentpeople;j++)

{

Swriter.write(StudentName[j]+"\t\t");

Swriter.write(StudentScore[j]+"\n");

}

Swriter.write("最高分:"+StudentScoreMax+"\n");

Swriter.write("最低分:"+StudentScoreMin+"\n");

}catch(IOException e){

e.printStackTrace();

}finally{

if(Swriter!=null)

try{

Swriter.close();

}catch(IOException e){}

}

Reader RStudent=null;

try{

RStudent=new FileReader("Student.txt");

char []buffer=new char[1024];

int offset;

while((offset=RStudent.read(buffer))0)

System.out.println(new String(buffer,0,offset));

}catch(FileNotFoundException e){

e.printStackTrace();

}catch(IOException e){

e.printStackTrace();

}finally{

if(RStudent!=null)

try{

RStudent.close();

}catch(IOException e){}

}

}

}

你可以参考着个程序 我自己写的

用java读取文件可以一边读取一边写入吗?如果我读取到某行数据,想用其它数据替换或者删除怎么写?

另外写一个文件,把有用的、需要改动的信息写入,最后删除原文件。


网站名称:java边读边写代码 java写代码技巧
本文URL:http://myzitong.com/article/dosphpg.html