现在的位置: 首页 > 综合 > 正文

Java基础——IO流和文件操作(下)

2018年03月22日 ⁄ 综合 ⁄ 共 23950字 ⁄ 字号 评论关闭

创建java文件列表

将一个指定目录下的java文件的绝对路径,存储到一个文件列表中,建立一个java文件列表文件

思路

1、对指定目录进行递归

2、获取递归过程中所得的java文件路径

3、将这些路径存储到集合中

package days16;

import java.io.*;

import java.util.ArrayList;

import java.util.Scanner;

public class FileList 

{

   public static void main(String[]args) throws IOException

   {

   while(true)

  {

   try 

   {

    System.out.println("请输入想打印的路径:");

   Scanner scr=new Scanner(System.in);

   String str=scr.next();

   File dir=new File(str);

   File file=new File("D:\\");

   ArrayList<File> al=new ArrayList<File>();

   long start=System.currentTimeMillis();

   list(dir,al);

   File files=new File(file,"保存路径.txt");

   write(al,files.toString());

   open();

   long end=System.currentTimeMillis();

   long time=end-start;

    if(time<=10000)

    System.out.println("本次执行共花费"+time+"毫秒");

    else

    if(time>10000&&time<=100000)

       System.out.println("本次执行共花费"+time/1000+"秒"); 

   }

    catch(Exception e)

  {

  System.out.println("路径格式错误,或者指定路径不存在!!!");

  System.out.println("请重新输入正确的路径名:");

  }

  }

  

  }

   

   public static void list(File dir,ArrayList<File> al)

   {

   File[]files=dir.listFiles();

   for(File f:files)

   {

   if(f.isDirectory())

   {

   list(f,al);

   }

   else

   {

   al.add(f);

   }

   }

   }

   public static void open() throws IOException //打开程序

   {

   

    Runtime r=Runtime.getRuntime();

   

    r.exec("cmd /k start D:\\保存路径.txt");//打开程序

   }

   public static void write(ArrayList<File> al,String dirs) throws IOException

   {

   BufferedWriter bufw=null;

   try

   {

bufw=new BufferedWriter(new FileWriter(dirs));

for(File f:al)

{

    System.out.println(f.getName()+"-----"+f.getAbsolutePath());

bufw.write(f.getName()+"-----"+f.getAbsolutePath());

    bufw.newLine();

    bufw.flush();

}

   }

   

   catch(IOException e)

   {

   System.out.println("写入失败!!!!");

   }

   

   finally

   {

   if(bufw!=null)

   {

   bufw.close();

   

   }

   }

   

   }

}

Properties

PropertiesHashtable的子类,也就是说它具备Map集合的特点,而且它里面存储的键值对都是字符串

是集合中和IO技术相结合的集合容器

该对象的特点:可以用于键对形式的配置文件

package days16;

import java.util.*;

public class Pro 

{

   public static void main(String[]args)

   {

   Properties prop=new Properties();

   prop.setProperty("zhangsan""30");

   prop.setProperty("lisi""31");

   System.out.println(prop);

   String value=prop.getProperty("lisi");

   System.out.println(value);

   prop.setProperty("lisi""89");

   Set<String>names=prop.stringPropertyNames();

   for(String s:names)

   {

   System.out.println(s+"::"+prop.getProperty(s));

   }

   }

}

Properties 存取配置文件

需求:想要将info.txt中键值数据存储到集合中进行存储

1、用一个流和info.txt关联

2、读取一行数据,将该行数据“=”进行切割

3、等号左边

package days16;

import java.io.*;

import java.util.*;

class Pro2

{

public static void main(String[] args) throws IOException

{

loadDemo();

}

public static void loadDemo() throws IOException

{

Properties prop=new Properties();

FileInputStream fis=new FileInputStream("C:\\info.txt");

prop.load(fis);

prop.setProperty("sss", "123");

FileOutputStream fos=new FileOutputStream("C:\\info.txt");

prop.store(fos, "hahahah");

prop.store(fos, "ddddddd");

System.out.println(prop);

fos.close();

fis.close();

}

}

Properties练习

用于记录应用程序运行次数。如果使用次数已到,那么给出注册提示。

    很容易想到的是:计数器。可是该计数器定义在程序中,随着程序的运行而在内存中存在,并进行自增。可是随着该应用程序的退出,该计数器也在内存中消失了。下一次在启动该程序,又重新开始从0计数。这样不是我们想要的。程序即使结束,该计数器的值也存在。

下次程序启动在会先加载该计数器的值并加1后在重新存储起来。所以要建立一个配置文件。用于记录该软件的使用次数。该配置文件使用键值对的形式。这样便于阅读数据,并操作数据。键值对数据是map集合。数据是以文件形式存储,使用io技术。

那么map+io -->properties.配置文件可以实现应用程序数据的共享。

package days16;

import java.io.*;

import java.util.*;

class  RunCount

{

public static void main(String[] args) throws IOException

{

   Properties prop=new Properties();

   File f=new File("D:\\count.ini");

   if(!f.exists())

   {

   f.createNewFile();

   }

   FileInputStream fis=new FileInputStream(f);

   int count=0;

   prop.load(fis);

   String value=prop.getProperty("time");

   if(value!=null)

   {

    count=Integer.parseInt(value);

    if(count>=5)

    {

     System.out.println("使用次数已到5次,试用期已满");

     return;

    }

   System.out.println("您已经使用了"+count+"");

   }

   

   count++;

   prop.setProperty("time", count+"");

   FileOutputStream fos=new FileOutputStream(f);

   prop.store(fos, "");

   fos.close();

   fis.close();

}

}

Print

打印流:

该流提供了打印方法,可以将各种数据类型的数据都原样打印。

字节打印流:

PrintStream

构造函数可以接收的参数类型:

1file对象。File

2,字符串路径。String

3,字节输出流。OutputStream

字符打印流:

PrintWriter

构造函数可以接收的参数类型:

1file对象。File

2,字符串路径。String

3,字节输出流。OutputStream

4,字符输出流,Writer

package days16;

import java.io.*;

class  Print

{

public static void main(String[] args) throws IOException

{

BufferedReader bufr = 

new BufferedReader(new InputStreamReader(System.in));

PrintWriter out = new PrintWriter(new FileWriter("D:\\demo.txt"),true);

String line = null;

while((line=bufr.readLine())!=null)

{

if("over".equals(line))

break;

out.println(line);

//out.flush();

}

out.close();

bufr.close();

}

}

合并流

package days16;

import java.io.*;

import java.util.*;

public class Sequence 

{

public static void main(String[]args) throws IOException

{

Vector<FileInputStream> v=new Vector<FileInputStream>();

v.add(new FileInputStream("D:\\demo.txt"));

v.add(new FileInputStream("D:\\demo2.txt"));

v.add(new FileInputStream("D:\\test.txt"));

Enumeration<FileInputStream> en=v.elements();

SequenceInputStream sis=new SequenceInputStream(en);

FileOutputStream fos=new FileOutputStream("D:\\sts.txt");

byte[]buf=new byte[1024];

int len=0;

while((len=sis.read(buf))!=-1)

{

fos.write(buf, 0, len);

}

fos.close();

sis.close();

}

}

切割文件

package days16;

import java.io.*;

public class Spilt1 

{

  public static void main(String[]args) throws IOException

  {

  FileInputStream fis=new FileInputStream("C:\\1.gif");

  byte[]buf=new byte[1024*1024];

  FileOutputStream fos=null;

  int len=0;

  int count=1;

  while((len=fis.read())!=-1)

  {

  fos=new FileOutputStream("D:\\split\\"+(count++)+".part");

  fos.write(buf, 0, len);

  fos.close();

  }

  fis.close();

  }

}

package days16;

import java.io.*;

import java.util.*;

public class Spilt2 

{

public static void main(String[]args) throws FileNotFoundException, IOException

{

ArrayList<FileInputStream> al = new ArrayList<FileInputStream>();

for(int x=1; x<=49333; x++)

{

al.add(new FileInputStream("D:\\split\\"+x+".part"));

}

final Iterator<FileInputStream> it = al.iterator();

Enumeration<FileInputStream> en = new Enumeration<FileInputStream>()

{

public boolean hasMoreElements()

{

return it.hasNext();

}

public FileInputStream nextElement()

{

return it.next();

}

};

SequenceInputStream sis = new SequenceInputStream(en);

FileOutputStream fos = new FileOutputStream("d:\\修.gif");

byte[] buf = new byte[1024];

int len = 0;

while((len=sis.read(buf))!=-1)

{

fos.write(buf,0,len);

}

fos.close();

sis.close();

}

}

对象序列化

package days17;

import java.io.Serializable;

public class Person implements Serializable

{

private String name;

transient int age;

static String country = "cn";

Person(String name,int age,String country)

{

this.name = name;

this.age = age;

this.country = country;

}

public String toString()

{

return name+":"+age+":"+country;

}

}

package days17;

import java.io.*;

import java.io.*;

class Str1

{

public static void main(String[] args) throws Exception

{

writeObj();

readObj();

}

public static void readObj()throws Exception

{

ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\obj.txt"));

Person p = (Person)ois.readObject();

System.out.println(p);

ois.close();

}

public static void writeObj()throws IOException

{

ObjectOutputStream oos = 

new ObjectOutputStream(new FileOutputStream("D:\\obj.txt"));

oos.writeObject(new Person("lisi0",399,"kr"));

oos.close();

}

}

To transient 修饰变量,不会被序列化,后缀名存为.Object

管道流

PipedInputStream PipedOutputStream

输入和输出可以直接进行连接,通过结合线程使用

package days17;

import java.io.*;

class Read implements Runnable

{

private PipedInputStream in;

Read(PipedInputStream in)

{

this.in = in;

}

public void run()

{

try

{

byte[] buf = new byte[1024];

System.out.println("读取前。。没有数据阻塞");

int len = in.read(buf);

System.out.println("读到数据。。阻塞结束");

String s= new String(buf,0,len);

System.out.println(s);

in.close();

}

catch (IOException e)

{

throw new RuntimeException("管道读取流失败");

}

}

}

class Write implements Runnable

{

private PipedOutputStream out;

Write(PipedOutputStream out)

{

this.out = out;

}

public void run()

{

try

{

System.out.println("开始写入数据,等待6秒后。");

Thread.sleep(6000);

out.write("piped lai la".getBytes());

out.close();

}

catch (Exception e)

{

throw new RuntimeException("管道输出流失败");

}

}

}

class  Pipe

{

public static void main(String[] args) throws IOException

{

PipedInputStream in = new PipedInputStream();

PipedOutputStream out = new PipedOutputStream();

in.connect(out);

Read r = new Read(in);

Write w = new Write(out);

new Thread(r).start();

new Thread(w).start();

}

}

Random AccessFile

随机访问文件 自身具备读写方法

通过skipBytiesint x)  seekint x)来达到随机访问

Random AccessFile——该类不算是IO体系中的类,而是直接继承自Object类,但是它是IO包中的成员,因为它具备读和写的功能

内部封装了一个数组,而且通过指针对数组元素进行操作,可以通过getFilePointer获取指针位置,同时可以通过seek改变指针位置,其实完成读写原理是内部封装了字节输入流和输出流,通过构造函数可以看出,该类只能操作文件。而且操作文件还有模式,只读r,读写rw等。而且该对象的构造函数操作的文件不存在,会自动创建,如果存在则不会覆盖

package days17;

import java.io.*;

public class Rand 

{

   public static void write_1() throws IOException

   {

   RandomAccessFile raf=new RandomAccessFile("D:\\ran.txt","rw");

   raf.write("李四".getBytes());

   raf.writeInt(97);

   raf.close();

   }

   

   public static void write_2() throws IOException

   {

   RandomAccessFile raf=new RandomAccessFile("D:\\ran.txt","rw");

   raf.seek(8*3);

   raf.write("张三".getBytes());

   raf.writeInt(97);

   raf.close();

   }

   

   public static void read()throws IOException

   {

   RandomAccessFile raf=new RandomAccessFile("D:\\ran.txt","r");

   raf.seek(8);

   raf.skipBytes(8);

   byte[]buf=new byte[16];

   String s=new String(buf);

   System.out.println(s);

   

   }

   

   public static void main(String[]args) throws IOException

   {

   write_2();

   read();

   }

}

模式只读r:不会创建文件,会去读取一个已经存在的文件,如果该文件不存在会出现异常

模式读写rw:操作的文件不存在,会自动创建,如果存在则不会覆盖

操作基本数据类型的流对象DataStream

操作基本数据类型

DataInputStreamDataOutputStream:可以用于指引基本数据类型的数据的该对象

操作字节数组

ByteArrayInputStreamByteArrayOutputStream

操作字符数组

charArrayReadcharArrayWrite

操作字符串

StringReaderStringWriter

package days17;

import java.io.*;

public class DataS 

{

public static void write() throws IOException

{

DataOutputStream dos=new DataOutputStream(new FileOutputStream("D:\\demo.txt"));

dos.writeInt(234);

dos.writeBoolean(true);

dos.writeDouble(9887.456);

dos.close();

}

public static void read() throws IOException

{

DataInputStream dis=new DataInputStream(new FileInputStream("D:\\demo.txt"));

int num=dis.readInt();

boolean b=dis.readBoolean();

double d=dis.readDouble();

System.out.println("num="+num);

System.out.println("b="+b);

System.out.println("d="+d);

dis.close();

}

public static void writeUTF() throws IOException

{

DataOutputStream dos=new DataOutputStream(new FileOutputStream("D:\\demo.txt"));

dos.writeUTF("你好");

dos.close();

}

public static void readUTF() throws IOException

{

DataInputStream dis=new DataInputStream(new FileInputStream("D:\\demo.txt"));

String s=dis.readUTF();

System.out.println(s);

dis.close();

}

public static void main(String[]args) throws IOException

{

write();

read();

writeUTF();

readUTF();

}

}

ByteArrayStream

用于操作字节数组的流对象

ByteArrayInputStream:在构造的时候,需要接受数据源,而且数据源是一个字节数组

ByteArrayOutputStream:在构造的时候,不用定义数据母的,因为该对象中内部已经封装了一个可变长度的字节数组,这就是数据目的地

因为这两个流对象都操作的是数组,并没有使用系统资源,所以不进行close关闭

在流操作规律讲解时:

源设备,

键盘 System.in,硬盘 FileStream,内存 ArrayStream

目的设备:

控制台 System.out,硬盘FileStream,内存 ArrayStream

用流的读写思想来操作数据。

package days17;

import java.io.*;

public class ByteARR 

{

public static void main(String[]args) throws IOException

{

ByteArrayInputStream bis=new ByteArrayInputStream("ABCDEFG".getBytes());

ByteArrayOutputStream bos=new ByteArrayOutputStream();

int by=0;

while((by=bis.read())!=-1)

{

bos.write(by);

}

System.out.println(bos.size());

System.out.println(bos.toString());

bos.writeTo(new FileOutputStream("D:\\demo.txt"));

}

}

转换流的字符编码

字符编码:字符流的出现是为了方便操作字符,更重要的是加入了编码转换,通过子类转换流来完成 InputStreamReader OutputStreamWriter 在两个对象进行构造的时候可以使用编码表

编码表的由来

计算机只识别二进制,早期由来是电信号,为了方便计算机,让他可以识别各个国家的文字,就将各个国家的文字用数字表示,并一一对应,形成一张表,这就是编码表

常见的编码表

ASCII——美国的标准信息交换码,用一个字节的7位可以表示

ISO8859-1——拉丁码表,欧洲码表,用一个字节的8位表示

GB2312——中国的中文编码表

GBK——中国的中文编码升级,融合了更多的中文编码表

Unicode——国际化标准码,融合了更多文字,所以文字都用两个字节来表示,jJva语言使用的是Unicode

UTF-8——最多用三个字节来表示一个字符

package days17;

import java.io.*;

public class Encode 

{

   public static void main(String[]args) throws IOException

   {

   write();

   read();

   }

   

   public static void read() throws IOException

   {

   InputStreamReader isr=new InputStreamReader(new FileInputStream("D:\\gbk.txt"),"GBK");

   char[]buf=new char[100];

   int len=isr.read(buf);

   String str=new String(buf,0,len);

   System.out.println(str);

   isr.close();

   }

   

   public static void write() throws IOException

   {

   OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream("D:\\gbk.txt"),"GBK");

   osw.write("你好!");

   osw.close();

   }

   

}

字符编码

编码:字符串变成字符数组

解码:字符数组变成字符串

String——>byte[ ]   str.getBytes();

Byte[ ]——>String   new String(byte[])

package days17;

import java.io.*;

import java.util.Arrays;

import java.util.*;

class  Encod

{

public static void main(String[] args)throws Exception 

{

String s = "哈哈";

byte[] b1 = s.getBytes("GBK");

System.out.println(Arrays.toString(b1));

System.out.println(new String(b1,0,b1.length));

String s1 = new String(b1,"utf-8");

System.out.println("s1="+s1);

//s1进行iso8859-1编码。

byte[] b2 = s1.getBytes("utf-8");

System.out.println(Arrays.toString(b2));

String s2 = new String(b2,"gbk");

System.out.println("s2="+s2);

}

}

联通

package days17;

import java.io.*;

public class Enco 

{

   public static void main(String[]args) throws IOException

   {

   String s="联通";

   byte[]by=s.getBytes("gbk");

   for(byte b:by )

   {

   System.out.println(Integer.toBinaryString(b));

   }

   }

}

练习

有五个学生,每个学生有三门课的成绩,从键盘中输入以上数据(包括姓名和三门课的成绩),输入的格式如张三,30,40,60,计算出总成绩,并把学生的信息和计算出的总分数,高低顺序存放在磁盘文件中:“student.txt

1、描述学生对象

2、定义一个可以操作对象的工具类

思想:

1、通过键盘导入一行数据,并将该行中数据中的信息取出并封装成学生对象

2、因为学生对象有很多,那么就需要存储,使用到集合,因为要对学生的总分进行排序

所以使用Tree-Set

3、将集合中的信息写入到一个文件中

package days17;

import java.io.*;

import java.util.*;

class Student implements Comparable<Student>

{

private String name;

private int ma,cn,en;

private int sum;

Student(String name,int ma,int cn,int en)

{

this.name = name;

this.ma = ma;

this.cn = cn;

this.en = en;

sum = ma + cn + en;

}

public int compareTo(Student s)

{

int num = new Integer(this.sum).compareTo(new Integer(s.sum));

if(num==0)

return this.name.compareTo(s.name);

return num;

}

public String getName()

{

return name;

}

public int getSum()

{

return sum;

}

public int hashCode()

{

return name.hashCode()+sum*78;

}

public boolean equals(Object obj)

{

if(!(obj instanceof Student))

throw new ClassCastException("类型不匹配");

Student s = (Student)obj;

return this.name.equals(s.name) && this.sum==s.sum;

}

public String toString()

{

return "student["+name+", "+ma+", "+cn+", "+en+"]";

}

}

class StudentInfoTool

{

public static Set<Student> getStudents()throws IOException

{

return getStudents(null);

}

public static Set<Student> getStudents(Comparator<Student> cmp)throws IOException

{

BufferedReader bufr = 

new BufferedReader(new InputStreamReader(System.in));

        

String line = null;

Set<Student> stus  = null;

if(cmp==null)

stus = new TreeSet<Student>();

else

stus = new TreeSet<Student>(cmp);

while((line=bufr.readLine())!=null)

{

if("over".equals(line))

break;

String[] info = line.split(",");

Student stu = new Student(info[0],Integer.parseInt(info[1]),

Integer.parseInt(info[2]),

Integer.parseInt(info[3]));

stus.add(stu);

}

bufr.close();

return stus;

}

public static void write2File(Set<Student> stus)throws IOException

{

BufferedWriter bufw = new BufferedWriter(new FileWriter("D:\\stuinfo.txt"));

for(Student stu : stus)

{

bufw.write(stu.toString()+"\t");

bufw.write(stu.getSum()+"");

bufw.newLine();

bufw.flush();

}

bufw.close();

}

}

class Stu 

{

public static void main(String[] args) throws IOException

{

Comparator<Student> cmp = Collections.reverseOrder();

Set<Student> stus = StudentInfoTool.getStudents(cmp);

StudentInfoTool.write2File(stus);

}

  

本周作品

package No1;

import java.io.*;

import java.util.*;

class Students 

{

  public int num;

  public String name;

  public String clas;

  public double ma;

  public double cn;

  public double en;

  public double sum;

  

  Students(int num,String name,String clas,double ma,double cn,double en)

  {

  this.num=num;

  this.name=name;

  this.clas=clas;

  this.ma=ma;

  this.cn=cn;

  this.en=en;

  sum=ma+cn+en;

  }

   

  public double getSum()

  {

  return sum;

  }

 

}

class NumCompare implements Comparator<Students>

{

public int compare(Students s1, Students s2) 

{

   int num=new Integer(s1.num).compareTo(s2.num);

   if(num==0)

   {

   return s1.name.compareTo(s2.name);

   }

   return num;

}

}

class SumCompare implements Comparator<Students>

{

public int compare(Students s1, Students s2) 

{

   int num=new Double(s2.sum).compareTo(s1.sum);

   if(num==0)

   {

   return s1.name.compareTo(s2.name);

   }

   return num;

}

}

class MathCompare implements Comparator<Students>

{

public int compare(Students s1, Students s2) 

{

   int num=new Double(s2.ma).compareTo(s1.ma);

   if(num==0)

   {

   return s1.name.compareTo(s2.name);

   }

   return num;

}

}

class ChineseCompare implements Comparator<Students>

{

public int compare(Students s1, Students s2) 

{

   int num=new Double(s2.cn).compareTo(s1.cn);

   if(num==0)

   {

   return s1.name.compareTo(s2.name);

   }

   return num;

}

}

class EnglishCompare implements Comparator<Students>

{

public int compare(Students s1, Students s2) 

{

   int num=new Double(s2.en).compareTo(s1.en);

   if(num==0)

   {

   return s1.name.compareTo(s2.name);

   }

   return num;

}

}

package No1;

import java.io.*;

import java.util.*;

class Tool implements Runnable

{

public static Set<Students> SaveToTree(Set<Students> stus) throws IOException

{

BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));

String line=null;

String[]info=null;

System.out.println("请依次输入学生的学号,姓名,班级,数学成绩,语文成绩,英语成绩,以空格键分开");

System.out.println("例:(01  张三  三年级二班  100 86 45)按回车键输入下一学生成绩,输入over停止");

boolean flag=true;

while((line=bufr.readLine())!=null)

 {

System.out.println("请按如下格式输入该学生的学号   姓名  班级  数学成绩  语文成绩  英语成绩  以空格键分开,回车键确认,输入over停止"); 

if("over".equals(line))

  {

      break;

  }

info=line.split(" ");

try

{

double m=new Double(info[3]);

double c=new Double(info[4]);

double e=new Double(info[5]);

Students stu=new Students(new Integer(info[0]),info[1],info[2],m,c,e);

if(!(m>=0&&m<=100))

{

   throw new RuntimeException("数学成绩不在指定的范围请重新输入"); 

}

if(!(c>=0&&c<=100))

{

   throw new RuntimeException("语文成绩不在指定的范围请重新输入"); 

}

if(!(e>=0&&e<=100))

{

   throw new RuntimeException("英语成绩不在指定的范围请重新输入"); 

}

stus.add(stu);

}

catch(Exception e)

{

System.out.println("存在非法输入,请检查您的书写格式是否正确,以及分数是否在0-100分之间,检查后请重新输入!!!");

}

 }

System.out.println("控制台上输出学生成绩列表");

System.out.println("排名\t学号\t\t姓名\t班级\t数学\t语文\t英语\t总分");

Iterator<Students> it=stus.iterator();

int number=1;

while(it.hasNext())

{

Students st=it.next();

System.out.println((number++)+"\t"+st.num+"\t\t"+st.name+"\t"+st.clas+"\t"+st.ma+"\t"+st.cn+"\t"+st.en+"\t"+st.sum);

}

// System.out.println("是否要对刚才输入的数据进行修改");

//List list = Arrays.asList(stus);

   while(true)

   {

   System.out.println("是否要把该成绩保存成文档格式?保存请输入1,不保存请输入2");

   

   BufferedReader bufr2=new BufferedReader(new InputStreamReader(System.in));

   String st=bufr2.readLine();

   int k=Integer.parseInt(st);

   if(k==1)

   {

   writetxt(stus);

   boolean flags=true;

   try

   {

       while(true)

   {

   System.out.println("请输入要保存文档的地址,例如:D:\\我的文档");

   BufferedReader bufr3=new BufferedReader(new InputStreamReader(System.in));

   String str=bufr3.readLine();

   File file=new File(str);

   System.out.println("请输入要保存文档的文件名,例如:成绩单");

   String str2=bufr3.readLine();

   String str3="\\"+str2+".txt";

   File files=new File(file,str3);

   copy(files);

   break;

   }

   }

   catch(EOFException e)

   {

   System.out.println("文件路径输入有误,请重新输入!!!");

   }

     System.out.println("文件存储成功,打开备份缓存文件浏览!!!");

     System.out.println("稍等5秒,开始为您打开缓存文件。");

     Run r=new Run();

     new Thread(r).start(); 

             

             //bufr.close();

     break;

   }

   else

   if(k==2)

   break;

   else

   {

   System.out.println("非法输入字符,请重新输入!!!");

   }

   }

return stus;

}

public static void writetxt(Set<Students> stus) throws IOException

{

BufferedWriter bufw=new BufferedWriter(new FileWriter("D:\\成绩单.txt" ));

    int number=1;

    bufw.write("排名\t学号\t\t姓名\t班级\t数学\t语文\t英语\t总分");

    bufw.newLine();

try{

    for(Students s:stus)

    {

     bufw.write((number++)+"\t"+s.num+"\t\t"+s.name+"\t"+s.clas+"\t"+s.ma+"\t"+s.cn+"\t"+s.en+"\t"+s.sum); 

     bufw.newLine();

     bufw.flush();

    }

}

catch(IOException e)

{

System.out.println("保存失败!!!");

}

finally

{

bufw.close();

}

System.out.println("保存成功,已经存入缓存文件,地址:D:\\成绩单.txt");

}

public static void copy(File files) throws IOException

{

BufferedReader bufr=new BufferedReader(new FileReader("D:\\成绩单.txt"));

BufferedWriter bufw=new BufferedWriter(new FileWriter(files));

String line=null;

while((line=bufr.readLine())!=null)

{

bufw.write(line);

bufw.newLine();

bufw.flush();

}

bufw.close();

}

public static void Prop() throws IOException

{

Properties prop=new Properties();

System.out.println("查找文件数据");

System.out.println("1——读取文件按照学号查找,2——读取文件按照姓名查找");

BufferedReader bu=new BufferedReader(new InputStreamReader(System.in));

int x=Integer.parseInt(bu.readLine());

if(x==1)

{

    System.out.println("请输入指定路径,例如:D:\\我的成绩.txt");

BufferedReader bu2=new BufferedReader(new InputStreamReader(System.in));

    String len=bu2.readLine();

File f=new File(len);

try

{

BufferedReader bufr=new BufferedReader(new FileReader(f));

String line=null;

System.out.println("恭喜您成功读取到文件信息!!!");

while((line=bufr.readLine())!=null)

{

System.out.println(line);

String []str=line.split("\t");

prop.setProperty(str[1], (str[0]+"\t"+str[2]+"\t"+str[3]+"\t"+str[4]+"\t"+str[5]+"\t"+str[6]+"\t"+str[7]));

}

//System.out.println(prop);

System.out.println("请输入要查找的学号");

BufferedReader buf=new BufferedReader(new InputStreamReader(System.in));

String key=buf.readLine();

String str=prop.getProperty(key);

if(str==null)

{

System.out.println("找不到该学生数据!!!");

}

else

{

System.out.println("查找成功!我们将为您在控制台上显示您要查找的内容。");

System.out.println("排名\t姓名\t班级\t数学\t语文\t英语\t总分\t");

System.out.println(str);

}

}

    

catch(IOException e)

{

System.out.println("读取文件不存在,或者书写路径格式有误。例如:D:\\我的成绩.txt");

}

}

else

if(x==2)

{

System.out.println("请输入指定路径,例如:D:\\我的成绩.txt");

BufferedReader bu2=new BufferedReader(new InputStreamReader(System.in));

    String len=bu2.readLine();

File f=new File(len);

try

{

BufferedReader bufr=new BufferedReader(new FileReader(f));

String line=null;

System.out.println("恭喜您成功读取到文件信息!!!");

while((line=bufr.readLine())!=null)

{

System.out.println(line);

String []str=line.split("\t");

prop.setProperty(str[2], (str[0]+"\t"+str[1]+"\t\t"+str[3]+"\t"+str[4]+"\t"+str[5]+"\t"+str[6]+"\t"+str[7]));

}

//System.out.println(prop);

System.out.println("请输入要查找的姓名");

BufferedReader buf=new BufferedReader(new InputStreamReader(System.in));

String key=buf.readLine();

String str=prop.getProperty(key);

if(str==null)

{

System.out.println("找不到该学生数据!!!");

}

else

{

System.out.println("查找成功!我们将为您在控制台上显示您要查找的内容。");

System.out.println("排名\t学号\t班级\t数学\t语文\t英语\t总分\t");

System.out.println(str);

}

}

    

catch(IOException e)

{

System.out.println("读取文件不存在,或者书写路径格式有误。例如:D:\\我的成绩.txt");

}

}

else

{

System.out.println("选项输入有误!!!");

}

}

public void run() 

{

 System.out.println("\t\t\t\t成绩管理系统");

try

{

    while(true)

{

System.out.println("欢迎使用学生管理系统,请输入数字12选择您需要的功能") ;

    System.out.println("1-读取文件成绩查询,2-写入学生成绩");

 BufferedReader bufa=new BufferedReader(new InputStreamReader(System.in));

String s=bufa.readLine();

int k=Integer.parseInt(s);

if(k==1)

{

Prop();

}

else

if(k==2)

{

Set<Students> stus=null;

System.out.println("请输入数字1——5,选择默认的排序显示方式");

System.out.println("1-按照学号顺序,2—按照总分成绩顺序,3-按照数学成绩顺序,4-按照语文成绩顺序,5-按照英语成绩顺序");

    BufferedReader bu2=new BufferedReader(new InputStreamReader(System.in));

    String li=bu2.readLine();

    int x=Integer.parseInt(li);

switch(x)

{

case 1: stus=new TreeSet<Students>(new NumCompare());SaveToTree(stus);break;

case 2: stus=new TreeSet<Students>(new SumCompare());SaveToTree(stus);break;

case 3: stus=new TreeSet<Students>(new MathCompare());SaveToTree(stus);break;

case 4: stus=new TreeSet<Students>(new ChineseCompare());SaveToTree(stus);break;

case 5: stus=new TreeSet<Students>(new EnglishCompare());SaveToTree(stus);break;

default:System.out.println("非法输入字符~~~~");

}

}

else

{

System.out.println("选项输入有误!!!");

}

}

}

catch(Exception e)

{

System.out.println("非法输入异常!!!");

e.toString();

}

}

}

class Run  implements Runnable

{

public  void run()  //打开程序

{

File f=new File("D:\\成绩单.txt");

try {

Thread.sleep(5000);

} catch (InterruptedException e1) {

System.out.println("出现错误,等待异常!");

e1.printStackTrace();

}

try

{

if(f.exists())

{

Runtime r=Runtime.getRuntime();

r.exec("cmd /k start D:\\成绩单.txt");//打开程序

}

}

catch(IOException e)

{

System.out.println("文件读取失败!!!");

}

}

}

class StudentInfo

{

public static void main(String[]args)

{

Tool t=new Tool();

Thread td=new Thread(t);

td.start();

}

}

抱歉!评论已关闭.