1. 程式人生 > >Java面向物件與多執行緒綜合實驗(三)之輸入輸出流

Java面向物件與多執行緒綜合實驗(三)之輸入輸出流

瞭解Java中I/O流的概念和種類;掌握位元組流處理和字元流處理,包括File類,InputStream/OutputStream及其子類,Reader/Writer及其子類;熟練掌握檔案的順序處理,隨機訪問處理;熟悉物件序列化的概念和方法。
編寫程式,實現檔案管理系統中的檔案上傳/下載模組。要求使用者登入系統後,可根據系統儲存資料,瀏覽已有檔案資料資訊;可根據檔案號,下載對應檔案檔案至指定目錄;可輸入並在系統中記錄新檔案資訊,並將對應的檔案檔案上傳至指定目錄。要求如下:

(1)完善showFileList()方法,實現檔案資訊瀏覽,在未講資料庫之前,系統中已存在檔案資訊放置在Hashtable中,提供新版DataProcessing類,該類實現了對應資料的查詢、插入操作。

(2)完善uploadFile()方法,實現檔案資料的上傳,在未講網路之前,該方法只需實現在指定目錄中讀取檔案,並將其拷貝至其他目錄中,此外還需將相關檔案資訊寫入對應Hashtable中。

(3)完善downloadFile(),實現檔案資料下載,目前只需要實現根據檔案號,在Hashtable中查詢得到檔案位置,然後讀取檔案並將其拷貝至指定目錄中。

  • User.java

import java.sql.SQLException;
import java.util.Enumeration;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public abstract class User {
     private String name;
     private String password;
     private String role;
     
     String uploadpath="C:\\uploadfile\\";
     String downloadpath="C:\\downloadfile\\";
     User(String name,String password,String role){
    	 this.name=name;
    	 this.password=password;
    	 this.role=role;
     }
     public abstract  void showMenu(String name);
     public void showFileList() throws SQLException{
    	 /*
    	 double ranValue=Math.random();
    	 if(ranValue>0.5) throw new SQLException("Error in accessing file DB");
    	 */
    	 Enumeration<Doc> e=null;
    	 try {
    		 e=DataProcessing.getAllDocs();
    	 }
    	 catch(SQLException e1) {
    		 System.out.println(e1.getMessage());
    	 }
    	 Doc doc;
    	 while(e.hasMoreElements()) {
    		 doc=e.nextElement();
    		 System.out.println("ID:"+doc.getID()+"\tCreator:"+doc.getCreator()+"\tTime:"+
    		 doc.getTimestamp()+"\tFilename:"+doc.getFilename()+"\tDescription:"+doc.getDescription());
    	 }
     }
     public boolean downloadFile(String ID) throws IOException{
    	 /*
    	 double ranValue=Math.random();
    	 if(ranValue>0.5) throw new IOException("Error in accessing file");
    	 */
    	 byte[] buffer=new byte[1024];
    	 Doc doc=null;
		 try {
			 doc = DataProcessing.searchDoc(ID);
		 } 
		 catch (SQLException e) {
			 System.out.println(e.getMessage());
		 }
    	 if(doc==null) return false;
    	 File tempFile=new File(uploadpath+doc.getFilename());
    	 String filename=tempFile.getName();
    	 BufferedInputStream infile=new BufferedInputStream(new FileInputStream(tempFile));
    	 BufferedOutputStream targetfile=new BufferedOutputStream(new FileOutputStream(new File(downloadpath+filename)));
    	 while(true) {
    		 int byteRead=infile.read(buffer);
    		 if(byteRead==-1)
    			 break;
    		 targetfile.write(buffer,0,byteRead);
    	 }
    	 infile.close();
    	 targetfile.close();
    	 return true;
     }
     public boolean changeSelfInfo(String password) throws SQLException{
    	if(DataProcessing.update(name,password,role)) {
    		this.password=password;
    		System.out.println("修改成功!");
    		return true;
    	}
    	else {
    		System.out.println("修改失敗!");
    		return false;
    	}
     }
     public void exitSystem() {
    	 System.out.println("系統退出,謝謝使用!");
    	 System.exit(0);
     }
     public void setName(String name) {
    	 this.name=name;
     }
     public String getName() {
    	 return name;
     }
     public void setPassword(String password) {
    	 this.password=password;
     }
     public String getPassword() {
    	 return password;
     }
     public void setRole(String role) {
    	 this.role=role;
     }
     public String getRole() {
    	 return role;
     }
}

  • DataProcessing.java

import java.util.Enumeration;
import java.util.Hashtable;
import java.sql.*;

public class DataProcessing {
	private static boolean connectToDB=false;
    static Hashtable<String,User> users;
    static Hashtable<String,Doc> docs;
    static {
    	users=new Hashtable<String,User>();
    	users.put("hjy", new Operator("hjy","111","operator"));
    	users.put("cr", new Browser("cr","000","browser"));
    	users.put("myk", new Administrator("myk","250","administrator"));
    	Init();
    	Timestamp timestamp=new Timestamp(System.currentTimeMillis());
    	docs=new Hashtable<String,Doc>();
    	docs.put("0001", new Doc("0001","hjy",timestamp,"Doc Source Java","Doc.java"));
    }
    public static void Init() {
    	//connect to database
   
    	//update database connection status
    	/*
    	if(Math.random()>0.2) connectToDB=true;
    	else connectToDB=false;
    	*/
    }
    public static Doc searchDoc(String ID)throws SQLException{
    	if(docs.containsKey(ID)) {
    		Doc temp=docs.get(ID);
    		return temp;
    	}
    	return null;
    }
    public static Enumeration<Doc> getAllDocs() throws SQLException{
    	Enumeration<Doc> e=docs.elements();
    	return e;
    }
    public static boolean insertDoc(String ID,String creator,Timestamp timestamp,String description,String filename)throws SQLException{
    	Doc doc;
    	if(docs.containsKey(ID)) return false;
    	else {
    		doc=new Doc(ID,creator,timestamp,description,filename);
    		docs.put(ID, doc);
    		return true;
    	}
    }
    public static User searchUser(String name) throws SQLException{
    	/*
    	if(!connectToDB) throw new SQLException("Not Connected to Database");
    	double ranValue=Math.random();
    	if(ranValue>0.5) throw new SQLException("Error in excecuting Query");
    	*/
    	if(users.containsKey(name)) {
    		return users.get(name);
    	}
    	return null;
    }
    public static User search(String name,String password) throws SQLException{
    	/*
    	if(!connectToDB) throw new SQLException("Not Connected to Database");
    	double ranValue=Math.random();
    	if(ranValue>0.5) throw new SQLException("Error in excecuting Query");
    	*/
    	if(users.containsKey(name)) {
    		User temp=users.get(name);
    		if(temp.getPassword().equals(password))
    			return temp;
    	}
    	return null;
    }
    public static Enumeration<User> getAllUser() throws SQLException{
    	/*
    	if(!connectToDB) throw new SQLException("Not Connected to Database");
    	double ranValue=Math.random();
    	if(ranValue>0.5) throw new SQLException("Error in excecuting Query");
    	*/
    	Enumeration<User> e=users.elements();
    	return e;
    }
    public static boolean update(String name,String password,String role) throws SQLException{
    	User user;
    	/*
    	if(!connectToDB) throw new SQLException("Not Connected to Database");
    	double ranValue=Math.random();
    	if(ranValue>0.5) throw new SQLException("Error in excecuting Query");
    	*/
    	if(users.containsKey(name)) {
    		if(role.equalsIgnoreCase("administrator"))
    			user=new Administrator(name,password,role);
    		else if(role.equalsIgnoreCase("operator"))
    			user=new Operator(name,password,role);
    		else
    			user=new Browser(name,password,role);
    		users.put(name, user);
    		return true;
    	}
    	else return false;
    }
    public static boolean insert(String name,String password,String role) throws SQLException{
    	User user;
    	/*
    	if(!connectToDB) throw new SQLException("Not Connected to Database");
    	double ranValue=Math.random();
    	if(ranValue>0.5) throw new SQLException("Error in executing Query");
    	*/
    	if(users.containsKey(name)) 
    		return false;
    	else {
    		if(role.equalsIgnoreCase("administrator"))
    			user=new Administrator(name,password,role);
    		else if(role.equalsIgnoreCase("operator"))
    			user=new Operator(name,password,role);
    		else
    			user=new Browser(name,password,role);
    		users.put(name, user);
    		return true;
    	}
    }
    public static boolean delete(String name) throws SQLException{
    	/*
    	if(!connectToDB) throw new SQLException("Not Connected to Database");
    	double ranValue=Math.random();
    	if(ranValue>0.5) throw new SQLException("Error in excecuting Query");
    	*/
    	if(users.containsKey(name)) {
    		users.remove(name);
    		return true;
    	}
    	else return false;
    }
    public void disconnectFromDB() {
    	if(connectToDB) {
    		//close Statement and Connection
    		try {
    			/*
    			if(Math.random()>0.5) throw new SQLException("Error in disconnecting DB");
    		}
    		catch(SQLException sqlException) {
    			sqlException.printStackTrace();
    			*/
    		}finally {
    			connectToDB=false;
    		}
    	}
    }
}

  • Doc.java

import java.sql.Timestamp;

class Doc{
	private String ID;
	private String creator;
	private Timestamp timestamp;
	private String description;
	private String filename;
	
	public Doc(String ID, String creator, Timestamp timestamp, String description, String filename) {
		super();
		this.ID = ID;
		this.creator = creator;
		this.timestamp = timestamp;
		this.description = description;
		this.filename=filename;
	}

	public String getID() {
		return ID;
	}

	public void setID(String iD) {
		ID = iD;
	}

	public String getCreator() {
		return creator;
	}

	public void setCreator(String creator) {
		this.creator = creator;
	}

	public Timestamp getTimestamp() {
		return timestamp;
	}

	public void setTimestamp(Timestamp timestamp) {
		this.timestamp = timestamp;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public String getFilename() {
		return filename;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

}

  • Administrator.java

import java.io.IOException;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Scanner;
public class Administrator extends User{
	private Scanner sc;
    Administrator(String name, String password, String role) {
		super(name, password, role);
	}
	public void changeUserInfo() {
		System.out.println("請輸入要修改的使用者姓名:");
    	String cn=sc.next();
    	System.out.println("請輸入新的使用者密碼:");
    	String cm=sc.next();
    	System.out.println("請輸入新的使用者角色:");
    	String cr=sc.next();
    	try {
			if(DataProcessing.update(cn, cm, cr)) {
				System.out.println("修改使用者資訊成功!");
			}
			else System.out.println("修改失敗!");
		} 
    	catch (SQLException e) {
    		System.out.println(e.getMessage());
		}
     }
    public void delUser() {
    	System.out.println("請輸入要刪除的使用者姓名:");
    	String dn=sc.next();
    	try {
			if(DataProcessing.delete(dn)) {
				System.out.println("刪除成功!");
			}
			else System.out.println("刪除失敗!該使用者不存在");
		} 
    	catch (SQLException e) {
    		System.out.println(e.getMessage());
		}
    }
    public void addUser() {
    	System.out.println("請輸入要增加的使用者姓名:");
    	String an=sc.next();
    	System.out.println("請輸入要增加的使用者密碼:");
    	String am=sc.next();
    	System.out.println("請輸入要增加的使用者角色:");
    	String ar=sc.next();
    	try {
			if(DataProcessing.insert(an, am, ar)) {
				System.out.println("增加使用者"+an+"成功!");
			}
			else System.out.println("增加使用者"+an+"失敗!");
		} 
    	catch (SQLException e) {
    		System.out.println(e.getMessage());
		}
    	
    }
    public void listUser() {
    	 Enumeration<User> e = null;
		try {
			e = DataProcessing.getAllUser();
		} 
		catch (SQLException e1) {
			System.out.println(e1.getMessage());
		}
    	 User user;
    	 while(e.hasMoreElements()) {
    		 user=e.nextElement();
    		 System.out.println("姓名:"+user.getName()+"密碼:"+user.getPassword()+"角色:"+user.getRole());
    	 }
    }
	public void showMenu(String name) {
		System.out.println("歡迎進入檔案操作員選單!");
    	System.out.println("1.修改使用者");
    	System.out.println("2.刪除使用者");
    	System.out.println("3.新增使用者");
    	System.out.println("4.列出使用者");
    	System.out.println("5.下載檔案");
    	System.out.println("6.檔案列表");
    	System.out.println("7.修改(本人)密碼");
    	System.out.println("8.退出");
    	sc=new Scanner(System.in);
    	int i=sc.nextInt();
    	switch(i) {
    	    case 1:{
    	    	changeUserInfo();
	    	    break;
    	    }
    	    case 2:{
	            delUser();
	            break;
    	    }
    	    case 3:{
    	        addUser();
    	    	break;
        	}
    	    case 4:{
    	        listUser();
    	        break;
        	}
    	    case 5:{
    	    	System.out.println("請輸入檔案編號:");
    	    	String ID=sc.next();
    	    	try {
					if(downloadFile(ID)) {
						System.out.println("下載成功!");
					}
					else System.out.println("下載失敗!");
				} 
    	    	catch (IOException e) {
    	    		System.out.println(e.getMessage());
				}
    	    	break;
    	    }
    	    case 6:{
    	    	try {
					showFileList();
				} 
    	    	catch (SQLException e) {
    	    		System.out.println(e.getMessage());
				}
    	    	break;
    	    }
    	    case 7:{
    	    	System.out.println("請輸入新密碼:");
    	    	String psd=sc.next();
    	    	try {
					changeSelfInfo(psd);
				} 
    	    	catch (SQLException e) {
    	    		System.out.println("檔案訪問錯誤"+e.getMessage());
				}
    	    	break;
    	    }
    	    case 8:{
    	    	exitSystem();
    	    }
    	    default:{
    	    	System.out.println("輸入非法!請重新輸入!");
    	    	break;
    	    }
    	}
    	showMenu(name);
	}
}

  • Operator.java

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Scanner;

public class Operator extends User{
	Operator(String name, String password, String role) {
		super(name, password, role);
	}
    public void showMenu(String name) {
    	System.out.println("歡迎進入檔案操作員選單!");
    	System.out.println("1.上傳檔案");
    	System.out.println("2.下載檔案");
    	System.out.println("3.檔案列表");
    	System.out.println("4.修改密碼");
    	System.out.println("5.退出");
    	@SuppressWarnings("resource")
		Scanner sc = new Scanner(System.in);
    	int i=sc.nextInt();
    	switch(i) {
    	    case 1:{
    	        try {
					uploadFile(name);
				} 
    	        catch (IOException e) {
					System.out.println(e.getMessage());
				}
    	        System.out.println("檔案上傳成功!");
    	        break;
        	}
    	    case 2:{
    	    	System.out.println("請輸入檔案編號:");
    	    	String ID=sc.next();
    	    	try {
					if(downloadFile(ID)) {
						System.out.println("下載成功!");
					}
					else System.out.println("下載失敗!");
				} 
    	    	catch (IOException e) {
    	    		System.out.println(e.getMessage());
				}
    	    	break;
    	    }
    	    case 3:{
    	    	try {
					showFileList();
				} 
    	    	catch (SQLException e) {
    	    		System.out.println(e.getMessage());
				}
    	    	break;
    	    }
    	    case 4:{
    	    	System.out.println("請輸入新密碼:");
    	    	String psd=sc.next();
    	    	try {
					changeSelfInfo(psd);
				} 
    	    	catch (SQLException e) {
    	    		System.out.println(e.getMessage());
				}
    	    	break;
    	    }
    	    case 5:{
    	    	exitSystem();
    	    }
    	    default:{
    	    	System.out.println("輸入非法!請重新輸入!");
    	    	break;
    	    }
    	}
    	showMenu(name);
    }
    public void uploadFile(String name) throws IOException{
    	System.out.println("請輸入原始檔名:");
    	@SuppressWarnings("resource")
		Scanner sc=new Scanner(System.in);
    	String filename=sc.next();
    	System.out.println("請輸入檔案號");
    	String ID=sc.next();
    	System.out.println("請輸入檔案描述");
    	String description=sc.next();
    	byte[] buffer=new byte[1024];
   	    Timestamp timestamp=new Timestamp(System.currentTimeMillis());
   	    File tempFile=new File(filename.trim());
        String fileName=tempFile.getName();
   	    try {
			if(DataProcessing.insertDoc(ID,name,timestamp,description,fileName)) ;
			else System.out.println("存入資料庫失敗!");
		} 
		catch (SQLException e) {
			System.out.println(e.getMessage());
		}
   	    BufferedInputStream infile = null;
	    infile = new BufferedInputStream(new FileInputStream(filename));
   	    BufferedOutputStream targetfile = null;
		targetfile = new BufferedOutputStream(new FileOutputStream(new File(uploadpath+fileName)));
   	    while(true) {
   		    int byteRead = 0;
		    byteRead = infile.read(buffer);
   		    if(byteRead==-1)
   		        break;
		    targetfile.write(buffer,0,byteRead);
   	    }
		infile.close();
		targetfile.close();
    }
}

  • Browser.java

import java.io.IOException;
import java.sql.SQLException;
import java.util.Scanner;
public class Browser extends User{
	Browser(String name, String password, String role) {
		super(name, password, role);
	}
	public void showMenu(String name) {
    	System.out.println("歡迎進入檔案瀏覽員選單!");
    	System.out.println("1.下載檔案");
    	System.out.println("2.檔案列表");
    	System.out.println("3.修改密碼");
    	System.out.println("4.退出");
    	System.out.print("請選擇:");
    	@SuppressWarnings("resource")
		Scanner sc = new Scanner(System.in);
    	int i=sc.nextInt();
    	switch(i) {
    	    case 1:{
    	    	System.out.println("請輸入檔案編號:");
    	    	String ID=sc.next();
    	    	try {
					if(downloadFile(ID)) {
						System.out.println("下載成功!");
					}
					else System.out.println("下載失敗!");
				} 
    	    	catch (IOException e) {
    	    		System.out.println(e.getMessage());
				}
    	    	break;
    	    }
    	    case 2:{
    	    	try {
					showFileList();
				} 
    	    	catch (SQLException e) {
    	    		System.out.println(e.getMessage());
				}
    	    	break;
    	    }
    	    case 3:{
    	    	System.out.println("請輸入新密碼:");
    	    	String psd=sc.nextLine();
    	    	try {
					changeSelfInfo(psd);
				} 
    	    	catch (SQLException e) {
    	    		System.out.println(e.getMessage());
				}
    	    	break;
    	    }
    	    case 4:{
    	    	exitSystem();
    	    }
    	    default:{
    	    	System.out.println("輸入非法!請重新輸入!");
    	    	break;
    	    }
    	}
    	showMenu(name);
    }
}

  • Main.java

import java.sql.SQLException;
import java.util.Scanner;
public class Main {
    public static void main(String args[]){
    	while(true) {
        	System.out.println("歡迎進入檔案管理系統!");
        	System.out.println("1.登入");
        	System.out.println("2.退出");
			@SuppressWarnings("resource")
			Scanner sc=new Scanner(System.in);
        	int i=sc.nextInt();
        	if(i==1) {
        		System.out.println("請輸入使用者名稱:");
        		String name=sc.next();
        		try {
					if(DataProcessing.searchUser(name)!=null) {
						System.out.println("請輸入密碼:");
						String password=sc.next();
						try {
						    if(DataProcessing.search(name ,password)!=null)
						        DataProcessing.search(name, password).showMenu(name);
						    else System.out.println("密碼錯誤!");  
						}
						catch(SQLException e) {
							System.out.println(e.getMessage());
						}
					}
					else {
					   System.out.println("使用者不存在!");   
					}
				} 
        		catch (SQLException e) {
        			System.out.println(e.getMessage());
				}
            }
        	else if(i==2) {
        		System.exit(0);
        	}
        	else {
        		System.out.println("輸入非法!請重新輸入。");
        	}
    	}
    }
}

以下是需要完成的結果展示:Java面向物件與多執行緒綜合實驗(三)之封裝、繼承與多型