天天看點

Java基礎——IO流和檔案操作(下)

建立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

Properties是Hashtable的子類,也就是說它具備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

構造函數可以接收的參數類型:

1,file對象。File

2,字元串路徑。String

3,位元組輸出流。OutputStream

字元列印流:

PrintWriter

構造函數可以接收的參數類型:

1,file對象。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

随機通路檔案 自身具備讀寫方法

通過skipByties(int x)  seek(int 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

操作基本資料類型

DataInputStream與DataOutputStream:可以用于指引基本資料類型的資料的該對象

操作位元組數組

ByteArrayInputStream與ByteArrayOutputStream

操作字元數組

charArrayRead與charArrayWrite

操作字元串

StringReader與StringWriter

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)按Enter鍵輸入下一學生成績,輸入over停止");

boolean flag=true;

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

 {

System.out.println("請按如下格式輸入該學生的學号   姓名  班級  數學成績  國文成績  英語成績  以空格鍵分開,Enter鍵确認,輸入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("歡迎使用學生管理系統,請輸入數字1或2選擇您需要的功能") ;

    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();

}

}