java編寫這個通訊錄管理系統(tǒng)
創(chuàng)新互聯(lián)建站長期為成百上千家客戶提供的網(wǎng)站建設(shè)服務(wù),團(tuán)隊(duì)從業(yè)經(jīng)驗(yàn)10年,關(guān)注不同地域、不同群體,并針對不同對象提供差異化的產(chǎn)品和服務(wù);打造開放共贏平臺,與合作伙伴共同營造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為陽朔企業(yè)提供專業(yè)的成都做網(wǎng)站、成都網(wǎng)站建設(shè)、成都外貿(mào)網(wǎng)站建設(shè),陽朔網(wǎng)站改版等技術(shù)服務(wù)。擁有十余年豐富建站經(jīng)驗(yàn)和眾多成功案例,為您定制開發(fā)。
java編寫這個通訊錄管理系統(tǒng)_Java如何實(shí)現(xiàn)通訊錄管理系統(tǒng)
咕嚕嚕在芬蘭
原創(chuàng)
關(guān)注
3點(diǎn)贊·2305人閱讀
Java如何實(shí)現(xiàn)通訊錄管理系統(tǒng)
發(fā)布時間:2020-07-28 09:39:42
來源:億速云
閱讀:65
作者:Leah
這篇文章將為大家詳細(xì)講解有關(guān)Java如何實(shí)現(xiàn)通訊錄管理系統(tǒng),文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。
本文實(shí)例為大家分享了java實(shí)現(xiàn)通訊錄管理系統(tǒng)的具體代碼,供大家參考,具體內(nèi)容如下
完成項(xiàng)目的流程:
1.根據(jù)需求,確定大體方向
2.功能模塊分析
3.界面實(shí)現(xiàn)
4.功能模塊設(shè)計(jì)
5.coding
6.代碼測試
下面是源代碼:import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.concurrent.SynchronousQueue;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
import javax.swing.text.html.HTMLDocument.Iterator;
class Infro{
public String id;
public String name;
public String sex;
public String address;
public String e_mail;
public String phoneNumber;
static int index = 0;
static ArrayList list = new ArrayList();
static int len = list.size();
//構(gòu)造函數(shù)
public Infro(String id,String name,String sex,String address,String e_mail,String phoneNumber){
this.id = id;
this.name = name;
this.sex = sex;
this.address = address;
this.e_mail = e_mail;
this.phoneNumber = phoneNumber;
}
public String toString(){
return "編號:"+id+" 姓名:"+name+" 性別:"+sex+" 通訊地址:"+address+" 郵箱地址:"+e_mail+" 電話:"+phoneNumber;
}
/**
* 添加功能
**/
public static void addFunction(){//添加功能
Infro infro = new Infro("","","","","","");
System.out.println("請輸入添加的數(shù)據(jù):");
Scanner in = new Scanner(System.in);
System.out.println("輸入編號:");
infro.id = in.next();
System.out.println("輸入姓名:");
infro.name = in.next();
System.out.println("輸入性別:");
infro.sex = in.next();
System.out.println("輸入通訊地址:");
infro.address = in.next();
System.
out.println("輸入郵箱地址:");
infro.e_mail = in.next();
System.out.println("輸入電話:");
infro.phoneNumber = in.next();
list.add(index,infro);
index++;
if(list.isEmpty()){
System.out.println("數(shù)據(jù)添加失敗啦");
}else{
System.out.println("數(shù)據(jù)添加成功啦");
len++;//list集合長度加一
// System.out.println(list.get(0).toString());
}
}
// public static void deleteFunction(){//刪除功能
// System.out.println("輸入要刪除的聯(lián)系人的編號");
// Scanner in_2 = new Scanner(System.in);
// String d1 = in_2.nextLine();
// for(int a= 0; a
// if(d1.equals(list.get(a).id)){
// list.remove(list.get(a));
// len --;
// }
// }
// }
/**
* 刪除功能
**/
public static void deleteFunction(){
System.out.println("輸入要刪除的聯(lián)系人的編號");
Scanner in_2 = new Scanner(System.in);
String d1 = in_2.nextLine();
java.util.Iterator it = list.iterator();
while (it.hasNext()){
Infro infro = it.next();
if (infro.id.equals(d1)){
it.remove();
--index;//一定要加這個,否則當(dāng)做了刪除操作再做添加操作的時候會出現(xiàn)異常(類似于指針,棧)
System.out.println("刪除完畢"+"此時通訊錄記錄條數(shù)為:" + --len);
}
}
}
/**
* 修改功能
**/
public static void reditFunction(){
System.out.println("輸入要修改的通訊錄的Id");
Scanner in_r = new Scanner(System.in);
String r1 = in_r.nextLine();
for(int a = 0; a len;a++){
if(r1.equals(list.get(a).id)){
System.out.println("輸入修改后的姓名:");
String name_1 = in_r.next();
list.get(a).name = name_1;
System.out.println("輸入修改后的性別:");
String sex_1 = in_r.next();
list.get(a).sex = sex_1;
System.out.println("輸入修改后的通訊地址:");
String address_1 = in_r.next();
list.get(a).address = address_1;
System.out.println("輸入修改后的郵箱地址:");
String e_mail_1 = in_r.next();
list.get(a).e_mail = e_mail_1;
System.out.println("輸入修改后的電話:");
String phoneNumber_1 = in_r.next();
list.get(a).phoneNumber = phoneNumber_1;
System.out.println("數(shù)據(jù)修改完畢");
}
}
}
/**
* 查詢功能
**/
public static void searchFunction() throws Exception{//查詢功能
System.out.println("請輸入要查詢的姓名:");
Scanner in_1 = new Scanner(System.in);
String s1=in_1.nextLine();
for(int a= 0; a
if(s1.equals(list.get(a).name)){
System.out.println(list.get(a).toString());
}
}
}
/**
* 顯示功能
**/
public static void showFunction(){
for(int i = 0 ;i
System.out.println(list.get(i).toString());
}
}
/**
* 保存功能
**/
public static void writeFunction() throws IOException{
FileWriter writer = new FileWriter("通訊錄管理.txt");
for(int i = 0 ;i
String []strwriter = new String[len];
strwriter[i]=list.get(i).toString();
writer.write(strwriter[i]);
writer.write("\r\n");
System.out.println("成功寫入一行數(shù)據(jù)到 通訊錄管理.txt 中");
}
writer.close();//關(guān)閉寫入流,釋放資源
}
/**
* 讀取功能
**/
public static void readFunction() throws IOException{
FileReader reader = new FileReader("通訊錄管理.txt");
BufferedReader br = new BufferedReader(reader);
String str;
while((str = br.readLine()) != null){//每次讀取一行文本,判斷是否到達(dá)文件尾
System.out.println(str);
}
br.close();
}
}
public class Demo extends JFrame {
/**
* 界面設(shè)計(jì)
**/
public Demo(){
Container c = getContentPane(); //定義一個頂級容器c
JPanel jp = new JPanel(); //新建JPanel面板--jp
JButton button1 = new JButton("新建聯(lián)系人");
JButton button2 = new JButton("刪除聯(lián)系人");
JButton button3 = new JButton("編輯聯(lián)系人");
JButton button4 = new JButton("查找聯(lián)系人");
JButton button5 = new JButton("顯示所有聯(lián)系人");
JButton button6 = new JButton("保存聯(lián)系人到本地");
JButton button7 = new JButton("讀取本地聯(lián)系人");
jp.setLayout(new GridLayout(2,4,5,5));//新建網(wǎng)格布局管理器(行數(shù),列數(shù),組件間的水平垂直間距)
jp.add(button1);
jp.add(button2);
jp.add(button3);
jp.add(button4);
jp.add(button5);
jp.add(button6);
jp.add(button7);
c.add(jp);//將JPanel面板jp添加到頂級容器c中
setSize(600,500);
setTitle("*通 訊 錄 管 理 系 統(tǒng)*");
setVisible(true);
setResizable(false);//窗體大小由程序員決定,用戶不能自由改變大小
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
/**
*按鍵響應(yīng)
*
**/
button1.addActionListener(new ActionListener(){//添加功能實(shí)現(xiàn)
public void actionPerformed(ActionEvent arg0){
Infro.addFunction();
}
});
button2.addActionListener(new ActionListener(){//刪除功能實(shí)現(xiàn)
public void actionPerformed(ActionEvent arg0){
Infro.deleteFunction();
}
});
button3.addActionListener(new ActionListener(){//修改功能實(shí)現(xiàn)
public void actionPerformed(ActionEvent arg0){
Infro.reditFunction();
}
});
button4.addActionListener(new ActionListener(){//查詢功能實(shí)現(xiàn)
public void actionPerformed(ActionEvent arg0){
try {
Infro.searchFunction();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
button5.addActionListener(new ActionListener(){//顯示功能實(shí)現(xiàn)
public void actionPerformed(ActionEvent arg0){
Infro.showFunction();
}
});
button6.addActionListener(new ActionListener(){//保存功能實(shí)現(xiàn)
public void actionPerformed(ActionEvent arg0){
try {
Infro.writeFunction();
} catch (IOException e) {
e.printStackTrace();
}
}
});
button7.addActionListener(new ActionListener(){//讀取功能實(shí)現(xiàn)
public void actionPerformed(ActionEvent arg0){
try {
Infro.readFunction();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new Demo();
Infro a = new Infro("", "", "", "", "", "");
}
}
關(guān)于Java如何實(shí)現(xiàn)通訊錄管理系統(tǒng)就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
開發(fā)環(huán)境JBuilder2005 SQL server2003 SP3連接方士直鏈,如果直鏈不上改橋鏈,參考
數(shù)據(jù)文件代碼:
create database userInfo
go
USE USERINFO
GO
create table uses(
username varchar(10) not null,
usertell varchar(20) not null,
usertells varchar(20) not null,
userQQ VARCHAR(20) NOT NULL,
USEREMAIL VARCHAR(20) NOT NULL,
USERADDRESS VARCHAR(20) NOT NULL
)
GO
Java部分代碼:
文件一窗體控制類 文件名 Application1.java
package myjava;
import java.awt.Toolkit;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import java.awt.Dimension;
public class Application1 {
boolean packFrame = false;
/**
* Construct and show the application.
*/
public Application1() {
Frame1 frame = new Frame1();
// Validate frames that have preset sizes
// Pack frames that have useful preferred size info, e.g. from their layout
if (packFrame) {
frame.pack();
} else {
frame.validate();
}
// Center the window
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = frame.getSize();
if (frameSize.height screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width screenSize.width) {
frameSize.width = screenSize.width;
}
frame.setLocation((screenSize.width - frameSize.width) / 2,
(screenSize.height - frameSize.height) / 2);
frame.setVisible(true);
}
/**
* Application entry point.
*
* @param args String[]
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(UIManager.
getSystemLookAndFeelClassName());
} catch (Exception exception) {
exception.printStackTrace();
}
new Application1();
}
});
}
}
文件二 數(shù)據(jù)庫驅(qū)動類文件名 DB.java
package myjava;
import java.sql.*;
/**
* pTitle: /p
*
* pDescription: /p
*
* pCopyright: Copyright (c) 2007/p
*
* pCompany: /p
*
* @author not attributable
* @version 1.0
*/
public class DB {
private String url = "jdbc:microsoft:sqlserver://";//SQLServer路徑
private String serverName = "localhost";//服務(wù)器名稱
private String portNumber = "1433";//端口號
private String databaseName = "userInfo";//數(shù)據(jù)庫名稱
private String userName = "sa";//登陸名
private String password = "sa";//密碼
private Connection con = null;
private Statement st=null;
private ResultSet rs=null;
public DB(){
}
public void setUrl(String url){
this.url=url;
}
public String getUrl(){
return this.url;
}
public void setServerName(String serverName){
this.serverName=serverName;
}
public String getServerName(){
return this.serverName;
}
public void setPortNumber(String portNumber){
this.portNumber=portNumber;
}
public String getPortNumber(){
return this.portNumber;
}
public void setDatabaseName(String databaseName){
this.databaseName=databaseName;
}
public String getdatabaseName(){
return this.databaseName;
}
public void setUserName(String userName){
this.userName=userName;
}
public String getUserName(){
return this.userName;
}
public void setUserPassword(String password){
this.password=password;
}
public String getPassword(){
return this.password;
}
//返回連接url
private String getConnectionUrl(){
return url + serverName + ":" + portNumber + ";databaseName=" +
databaseName + ";";
}
//獲得數(shù)據(jù)庫聯(lián)接驅(qū)動
public Connection getConnection(){
try {
//加載驅(qū)動
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
return null;
}
try {
//獲得驅(qū)動對象
con = DriverManager.
getConnection(getConnectionUrl(), userName,password);
} catch (SQLException ex1) {
ex1.printStackTrace();
return null;
}
return con;
}
//獲得連接對象
public Statement getStatement(){
try {
st = getConnection().createStatement();
} catch (SQLException ex) {
ex.printStackTrace();
return null;
}
return st;
}
//獲得結(jié)果集
public ResultSet getResultSet(String sql){
try {
rs = getStatement().executeQuery(sql);
} catch (SQLException ex) {
ex.printStackTrace();
return null;
}
return rs;
}
//更新數(shù)據(jù)庫信息
public int getUpdate(String sql){
try {
return getStatement().executeUpdate(sql);
} catch (SQLException ex) {
ex.printStackTrace();
return 0;
}
}
//數(shù)據(jù)關(guān)閉驅(qū)動對象
public void close(){
try {
con.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
//關(guān)閉連接對象
public void closeStatement(){
try {
if(st!=null){st.close();}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
//關(guān)閉結(jié)果集
public void closeRestultSet(){
if(rs!=null){
try {
rs.close();
} catch (SQLException ex) {
}
}
}
}
文件三 封裝用戶信息類 文件名userInfo.java
package myjava;
public class userInfo {
private String uesrName;
private String userTell;
private String userTellS;
private String userQQ;
private String userEmail;
private String userAdderss;
public userInfo() {
}
public void setUesrName(String uesrName) {
this.uesrName = uesrName;
}
public void setUserTell(String userTell) {
this.userTell = userTell;
}
public void setUserTellS(String userTellS) {
this.userTellS = userTellS;
}
public void setUserQQ(String userQQ) {
this.userQQ = userQQ;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
public void setUserAdderss(String userAdderss) {
this.userAdderss = userAdderss;
}
public String getUesrName() {
return uesrName;
}
public String getUserTell() {
return userTell;
}
public String getUserTellS() {
return userTellS;
}
public String getUserQQ() {
return userQQ;
}
public String getUserEmail() {
return userEmail;
}
public String getUserAdderss() {
return userAdderss;
}
}
文件四 操作控制類文件名 Frame1.java
package myjava;
import java.awt.*;
import javax.swing.*;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Frame1 extends JFrame {
JPanel contentPane;
JLabel jLabel1 = new JLabel();
JLabel jLabel2 = new JLabel();
JLabel jLabel3 = new JLabel();
JLabel jLabel4 = new JLabel();
JLabel lblName = new JLabel();
JLabel jLabel6 = new JLabel();
JTextField txtTell = new JTextField();
JTextField txtTellS = new JTextField();
JTextField txtQQ = new JTextField();
JTextField txtEamil = new JTextField();
JTextField txtAddress = new JTextField();
JTextField txtName = new JTextField();
JButton jButton1 = new JButton();
JButton jButton2 = new JButton();
public Frame1() {
try {
setDefaultCloseOperation(EXIT_ON_CLOSE);
jbInit();
} catch (Exception exception) {
exception.printStackTrace();
}
}
/**
* Component initialization.
*
* @throws java.lang.Exception
*/
private void jbInit() throws Exception {
contentPane = (JPanel) getContentPane();
contentPane.setLayout(null);
setSize(new Dimension(400, 488));
setTitle("Frame Title");
jLabel1.setText("電話");
jLabel1.setBounds(new Rectangle(23, 83, 101, 39));
jLabel2.setText("手機(jī)");
jLabel2.setBounds(new Rectangle(23, 138, 101, 39));
jLabel3.setText("QQ");
jLabel3.setBounds(new Rectangle(23, 197, 101, 39));
jLabel4.setText("Email");
jLabel4.setBounds(new Rectangle(23, 261, 101, 39));
lblName.setText("姓名");
lblName.setBounds(new Rectangle(23, 33, 101, 39));
jLabel6.setText("地址");
jLabel6.setBounds(new Rectangle(23, 329, 101, 39));
txtTell.setBounds(new Rectangle(120, 89, 260, 33));
txtTellS.setBounds(new Rectangle(120, 146, 260, 33));
txtQQ.setBounds(new Rectangle(120, 199, 260, 33));
txtEamil.setSelectionStart(11);
txtEamil.setBounds(new Rectangle(120, 257, 260, 33));
txtAddress.setBounds(new Rectangle(120, 324, 260, 33));
txtName.setBounds(new Rectangle(120, 41, 260, 33));
jButton1.setBounds(new Rectangle(250, 405, 130, 36));
jButton1.setText("查找");
jButton1.addActionListener(new Frame1_jButton1_actionAdapter(this));
jButton2.setBounds(new Rectangle(29, 404, 130, 36));
jButton2.setText("添加");
jButton2.addActionListener(new Frame1_jButton2_actionAdapter(this));
contentPane.add(jLabel1);
contentPane.add(jLabel2);
contentPane.add(jLabel3);
contentPane.add(jLabel4);
contentPane.add(lblName);
contentPane.add(jLabel6);
contentPane.add(txtName);
contentPane.add(txtTell);
contentPane.add(txtTellS);
contentPane.add(txtQQ);
contentPane.add(txtEamil);
contentPane.add(txtAddress);
contentPane.add(jButton2);
contentPane.add(jButton1);
}
//判斷輸入的內(nèi)容長度是否合法
private boolean Is(String str,int conut){
boolean is=false;
if(str==null||str.equals("")||str.length()conut){
is=true;
}
return is;
}
//判斷是否為字符,不能含有空白字符
private boolean IsLetter(String str,int Count){
boolean is=false;
if(Is(str,Count)){
return is=true;
}
for(int i=0;istr.length();i++){
char ch=str.charAt(i);
if(!Character.isLetter(ch)){
return is=true;
}
}
return is=false;
}
//判斷是否為數(shù)字,不能含有空白字符
private boolean IsNumber(String str,int conut){
boolean is=false;
if(Is(str,conut)){
return is=true;
}
for(int i=0;istr.length();i++){
char ch=str.charAt(i);
if(!Character.isDigit(ch)ch!='-'){
return is=true;
}
}
return is=false;
}
//判斷郵箱是否合法
private boolean IsEmail(String Email,int count){
boolean is=false;
if(Is(Email,count)){
return is=true;
}
int index1=Email.indexOf("@");
int index2=Email.indexOf(".");
if(index1==-1||index2==-1||index1index2){
return is=true;
}
return is;
}
//獲得用戶信息對象
private userInfo getInfo(){
userInfo u=new userInfo();
String name=txtName.getText().trim();
String Tell=txtTell.getText().trim();
String TellS=txtTellS.getText().trim();
String QQ=txtQQ.getText().trim();
String Email=txtEamil.getText().trim();
String Address=txtAddress.getText().trim();
//判斷姓名和地址
if(IsLetter(name,5)||IsLetter(Address,20)){
JOptionPane.showMessageDialog(this,"姓名或地址有誤,數(shù)字填寫只能含有'-'");
return null;
}
//判斷郵箱是否合法
if(IsEmail(Email,16)){
JOptionPane.showMessageDialog(this,"郵箱填寫有誤!");
return null;
}
//判斷聯(lián)系方式中數(shù)字部分是否合法
if(IsNumber(Tell,12)||IsNumber(TellS,12)||IsNumber(QQ,12)){
JOptionPane.showMessageDialog(this,"填寫聯(lián)系方法有誤,數(shù)字填寫只能含有'-'");
return null;
}
u.setUesrName(name);
u.setUserTell(Tell);
u.setUserTellS(TellS);
u.setUserQQ(QQ);
u.setUserEmail(Email);
u.setUserAdderss(Address);
return u;
}
private int Insert(userInfo u){
DB D=new DB();
int i=0;
if(u!=null){
String sql="insert into uses values(?,?,?,?,?,?)";
try {
PreparedStatement ps = D.getConnection().prepareStatement(sql);
ps.setString(1,u.getUesrName());
ps.setString(2,u.getUserTell());
ps.setString(3,u.getUserTellS());
ps.setString(4,u.getUserQQ());
ps.setString(5,u.getUserEmail());
ps.setString(6,u.getUserAdderss());
i=ps.executeUpdate();
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this,"系統(tǒng)錯誤,添加失敗!"+ex.getMessage());
return i;
}finally{
D.close();
}
}
return i;
}
private void getuserInfo(String userName) {
boolean is=false;
DB D=new DB();
if(IsLetter(userName,5)){
JOptionPane.showMessageDialog(this,"姓名不合法!");
return;
}
String sql="select * from uses where username=?";
try {
PreparedStatement ps = D.getConnection().prepareStatement(sql);
ps.setString(1,userName);
ResultSet rs=ps.executeQuery();
if(!rs.next()){
JOptionPane.showMessageDialog(this,"查詢信息不存在!");
}else{
txtName.setText(rs.getString(1));
txtTell.setText(rs.getString(2));
txtTellS.setText(rs.getString(3));
txtQQ.setText(rs.getString(4));
txtEamil.setText(rs.getString(5));
txtAddress.setText(rs.getString(6));
}
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this,"系統(tǒng)錯誤!"+ex.getMessage());
return;
}finally{
D.close();
}
}
//添加按鈕監(jiān)聽器
public void jButton2_actionPerformed(ActionEvent e) {
if(Insert(getInfo())==0){
JOptionPane.showMessageDialog(this,"添加信息失敗!");
}
}
//查詢按鈕監(jiān)聽方法
public void jButton1_actionPerformed(ActionEvent e) {
getuserInfo(txtName.getText().trim());
}
}
class Frame1_jButton1_actionAdapter implements ActionListener {
private Frame1 adaptee;
Frame1_jButton1_actionAdapter(Frame1 adaptee) {
this.adaptee = adaptee;
}
public void actionPerformed(ActionEvent e) {
adaptee.jButton1_actionPerformed(e);
}
}
class Frame1_jButton2_actionAdapter implements ActionListener {
private Frame1 adaptee;
Frame1_jButton2_actionAdapter(Frame1 adaptee) {
this.adaptee = adaptee;
}
public void actionPerformed(ActionEvent e) {
adaptee.jButton2_actionPerformed(e);
}
}
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class AddList {
private String filePath = "";
private String bakPath = "";
private String content = "";
Scanner sc = new Scanner(System.in);
public String readFile(){
content = "";
if (isNull(filePath)) {
System.out.println("文件存儲路徑:");
filePath = sc.nextLine();
}
File file = new File(filePath);
FileReader fr = null;
try {
if (file.exists()) {
fr = new FileReader(file);
char[] chars = new char[1024];
int n = 0;
while((n = fr.read(chars)) != -1){
String string = new String(chars, 0, n);
content = content + string;
}
} else {
System.out.println("文件不存在");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fr != null) {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return content;
}
public void writeFile(String path){
File file = new File(path);
FileOutputStream fos = null;
mkDirs(path);
try {
fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
PrintWriter pw = new PrintWriter(bos, true);
pw.print(content);
pw.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void writeFile(){
if (isNull(filePath)) {
System.out.println("文件存儲路徑:");
filePath = sc.nextLine();
}
File file = new File(filePath);
FileOutputStream fos = null;
mkDirs(filePath);
try {
fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
PrintWriter pw = new PrintWriter(bos, true);
pw.print(content);
pw.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void mkDirs(String filepath){
if (filepath.indexOf("\\") != -1) {
filepath = filepath.replaceAll("\\", "/");
}
int n = filepath.indexOf("http://");
String path = filepath.substring(0, n) + "http://";
filepath = filepath.substring(filepath.indexOf("http://") + 1, filepath.length());
String[] files = filepath.split("/");
for (int i = 0; i files.length - 1; i++) {
path = path + files[i];
File file = new File(path);
if (!file.exists()) {
file.mkdir();
}
}
}
public void addImfor(){
System.out.println("--------增加記錄---------");
String name = "";
String tel = "";
String email = "";
content = readFile();
while(true){
System.out.println("姓名:");
name = sc.next();
System.out.println("電話:");
tel = sc.next();
System.out.println("Email:");
email = sc.next();
content = content + name + "" + tel + "" + email +"==";
System.out.println("0、Exit 1、繼續(xù)");
int i = sc.nextInt();
if (i == 0) {
break;
}
}
writeFile();
}
public void deleteImfor(){
System.out.println("---------刪除記錄---------");
String name = "";
String[] imfors = null;
content = readFile();
while(true){
System.out.println("你要刪除的姓名是:");
name = sc.next();
if (content.indexOf(name) != -1) {
imfors = content.split("==");
for (int i = 0; i imfors.length; i++) {
if (imfors[i].indexOf(name) != -1) {
imfors[i] = "";
}
}