实验04 - Java输入输出流报告

更新时间:2023-12-31 02:20:01 阅读量: 教育文库 文档下载

说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。

实验四 Java 输入输出流

import java.util.Scanner;

public class CommandOutPut { /**

* @param args */

public static void main(String[] args) { // TODO Auto-generated method stub }

System.out.println(\:\); Scanner in = new Scanner(System.in); String str = in.nextLine();

System.out.println(\:\); System.out.println(str); in.close(); }

实验题2 通过键盘输入路径,搜索指定路径下的全部内容。

package cn.edu.jp;

import java.io.BufferedReader; import java.io.File;

import java.io.IOException; import java.io.InputStreamReader; public class alldir {

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

// TODO Auto-generated method stub //打印指定路径下所有的文件 String path = null;

System.out.println(\BufferedReader in = null;

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

path=in.readLine();

File file = new File(path);

System.out.println(path+\路径下的所有文件如下:\\n\File[] allfile = file.listFiles(); for(File f : allfile)

System.out.println(f.getName());

}

- 1 -

}

实验题3设计一个类FileRWTest,实现从input.txt文件中读入数据到字符数组cBuffer中,然后再写入到文件“output.txt”中。

package cn.edu.fileRWTester; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class FileRWTest { /**

* @param args

* @throws IOException */

public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader source = new BufferedReader(new FileReader(\)); BufferedWriter target = new BufferedWriter(new FileWriter(\));

//byte[] cBuffer = new byte[(int)((CharSequence) source).length()]; }

}

String temp = null;////将字节流转换为字符串

while ((temp = source.readLine()) != null) { target.write(temp); target.newLine(); target.flush(); }

source.close(); target.close();

实验题4 建立一个书籍信息的文本文件,其中包括编号、书籍名称、版本、价格、销售额字段及5本书籍的记录。编写程序读入书籍信息文件并将第3本、第4本书籍价格分别增加20和30,再将修改后的书籍信息文件输出到另一个文本文件中(文件名称为book.txt)。

文本文件book.txt内容如下:

编号 名称 版本 价格 销售额

1001 1002 1003 1004

Java程序设计 Java开发实战 C++程序设计指南 EJB3.0入门经典

第2版 第1版 第3版 第1版

56.9 98.9 62.5 59.8

560 820 362 1280

1005 Spring3.0 in Action 第3版 95.8 1189 设计思路:首先建立一个Book类,定义属性private String num,private String name,private

- 2 -

String edition,private Float price,private Float slaes,在主函数中创建5个实例,并把值赋给String text,然后调用target.write()函数写入文件book里。 检测是否写入,用read()函数读出: package cn.edu.Input.tester; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import cn.edu.Input.clas.Book; public class InputTester { /**

* @param args

* @throws IOException */

public static void main(String[] args) throws IOException { // TODO Auto-generated method stub }

}

Book b1 = new Book(\, \程序设计\, \第2版\, 56.9F, 560f); Book b2 = new Book(\, \开发实战\, \第1版\, 98.9f, 820f); Book b3 = new Book(\, \程序设计指南\, \第3版\, 62.5f, 362f); Book b4 = new Book(\, \入门经典\, \第1版\, 59.8f, 1280f); Book b5 = new Book(\, \in Action\, \第3版 \, 95.8f, 1189f); Book[] books = { b1, b2, b3, b4, b5 }; String text = null;

for (int index = 0; index < books.length; ++index) { text += books[index]; text += '\\n'; }

BufferedWriter target = new BufferedWriter(new FileWriter( \)); target.write(text); target.flush();

实验题5 有四个类,主类Store在包cn.edu.nwsuaf.jp.p4中,Mobile、Mp3Player、Product在包cn.edu.nwsuaf.jp.p4.data中,Mobile、Mp3Player是Product类的子类, Product类实现Seralizable接口。

基本要求:

(1)在Store类中用ObjectOutputStream类的对象把Mobile、Mp3Player类对象输出到文件“product.txt”中。

(2)在Store类中用ObjectInputStream类的对象从文件“product.txt”输入数据并将其输出。 实验设计:在product中重写writeObject和raedObject函数,并在主函数中调用writeObject和raedObject函数对文件读写。

代码:

Product中的writeObject和raedObject函数:

private void writeObject(ObjectOutputStream oos) throws IOException { oos.defaultWriteObject(); oos.writeBytes(getName());

- 3 -

oos.writeFloat(getPrice()); }

private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundExceptin { ois.defaultReadObject();

主函数:

package cn.edu.nwsuaf.jp.p4; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException;

import java.io.ObjectInputStream; import java.io.ObjectOutputStream;

import cn.edu.nwsuaf.jp.p4.data.Mobile; import cn.edu.nwsuaf.jp.p4.data.Mp3Player; public class Store { /**

* @param args */

public static void main(String[] args) throws IOException, ClassNotFoundException { try {

Mp3Player p1 = new Mp3Player(\, 399.0f); Mp3Player p2 = new Mp3Player(\, 580.0f);

Mp3Player p3 = new Mp3Player(\, 930.0f); Mobile m1 = new Mobile(\, 1780.0f); Mobile m2 = new Mobile(\, 1450.0f); ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream(\)); oos.writeObject(p1); oos.writeObject(p2); oos.writeObject(p3); oos.writeObject(m1); oos.writeObject(m2); oos.close();

ObjectInputStream ois = new ObjectInputStream(new FileInputStream( \));

while ((ois.readObject()) != null) {

System.out.println(ois.readObject()); }

ois.close();

} catch (Exception e) { e.printStackTrace(); } } }

- 4 -

2.实验内容

实验题1 学生信息管理函数。

实验八 Jdbc编程

创建student表,包含学生的学号、姓名、年龄信息。 ① 根据学号,可以查询到学生的姓名和年龄;

② 给定学生的学号、姓名、年龄,在表中追加一行信息; ③ 给定学生的学号,可以从表中删除该学生的信息; [基本要求] 对上面的每一个功能编写相应的函数,并测试。

package cn.edu.jp;

import cn.edu.jp.data.student; public class studenttest { }

package cn.edu.jp.data; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class student {

private static final String URL = \

- 5 -

/**

* @param args */

public static void main(String[] args) { }

// TODO Auto-generated method stub student stu = new student();

String sql = \; String sqll= \; String sqlk = \;

String sqlp = \; stu.searchRecordsByElement(sql); stu.insertOneRecord(sqll); stu.deleteOneRecord(sqlk); stu.updateOneRecord(sqlp);

//sql = \ //stu.deleteOneRecord(sql);

//sql = \ //stu.insertOneRecord(sql);lue

private static final String USERNAME = \private static final String PASSWORD = \ public static Connection conn = null; public student() { }

public void searchRecordsByElement(String sql){ }

public void insertOneRecord(String sql){ }

public void deleteOneRecord(String sql) {

try {

//sql = \Statement pst = conn.createStatement();

- 6 -

try

{//加载MySQL的驱动类,并创建数据库连接 Class.forName(\

conn=DriverManager.getConnection(URL,USERNAME,PASSWORD); Statement stat=conn.createStatement();//创建Statement对象

System.out.println(\加载成功\}

catch(Exception e) {//捕获异常,并打印出来 e.printStackTrace(); }

//String sql = \ try { }

Statement st= conn.createStatement(); ResultSet result = st.executeQuery(sql); while(result.next()){ }

e.printStackTrace();

System.out.println(result.getString(1)+\

} catch (SQLException e) {

try { }

Statement stm = conn.createStatement(); stm.executeUpdate(sql);

System.out.println(\插入成功。\stm.close(); conn.close();

} catch (SQLException e) { e.printStackTrace();

}

}

pst.executeUpdate(sql); pst.close(); conn.close();

System.out.println(\删除成功。\} catch (SQLException e) {

e.printStackTrace(); }

public void updateOneRecord(String sql) { }

try {

//sql = \Statement ps = conn.createStatement(); ps.executeUpdate(sql); ps.close(); conn.close();

System.out.println(\更新成功。\} catch (SQLException e) {

e.printStackTrace(); }

实验题2 Jdbc编程。在MySql数据库的test库中,建一个表student,其内容如下表所示,

将表中score大于60的记录的信息输出到控制台。 学生信息表

Id 1002 1003 1004 1005 1006 package cn.student.jp.data; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Student {

private static final String URL = \; private static final String USERNAME = \; private static final String PASSWORD = \;

- 7 -

Name Tom Mary Peter John polo Gender male female male male female Score 80 89 54 76 90

}

public static Connection conn = null; public Student() { }

public void searchRecordsByElement(String sql) { }

// String sql = \ try { }

Statement st = conn.createStatement(); ResultSet result = st.executeQuery(sql); /*

* DatabaseMetaData metadata = conn.getMetaData(); ResultSet res = * metadata.getColumns(null, null,\ *

* int i = 0; while(res.next()){ i++; } System.out.println(i); */

System.out.println(\ + \ + \ + \); while (result.next()) { }

e.printStackTrace();

System.out.println(result.getString(1) + \

+ result.getString(2) + \ + result.getString(3) + \ + result.getString(4));

try {// 加载MySQL的驱动类,并创建数据库连接 Class.forName(\);

conn = DriverManager.getConnection(URL, USERNAME, PASSWORD); Statement stat = conn.createStatement();// 创建Statement对象 System.out.println(\加载成功\);

} catch (Exception e) {// 捕获异常,并打印出来 e.printStackTrace(); }

} catch (SQLException e) {

package cn.student.jp;

import cn.student.jp.data.Student; public class qtest {

/**

* @param args */

public static void main(String[] args) {

// TODO Auto-generated method stub

Student stu = new Student();

String sql = \; stu.searchRecordsByElement(sql); }

- 8 -

}

实验题3 熟悉课堂内容,学习掌握数据库访问编程实现的程序结构。

(1)设计一个与连接数据库相关接口UserDao(访问数据库——增、删、改、查——DAO(Data Access Object,数据访问对象),一般针对不同的数据库表采用不同的DAO功能实现类。)

(2)设计持久实体类(PO)——封装装数据库表中的各个字段

(3)设计一个类,实现UserDao接口,完成访问数据库的相关操作(增、删、改、查); (4)设计一个类,测试UserDao的实现类。

(5)修改daoconfig.properties文件,切换UserDao的实现。 package cn.jp; import java.util.Date; import cn.jp.data.User; import cn.jp.data.UserDaoImpl; public class UserDaotest {

/**

* @param args */

public static void main(String[] args) {

// TODO Auto-generated method stub UserDaoImpl udi = new UserDaoImpl(); User user1 = new User(); user1.setId(201101); user1.setName(\张三%user1.setBirthday(new Date()); user1.setMoney(2222); User user2 = new User(); user2.setId(201102); user2.setName(\李四%user2.setBirthday(new Date()); user2.setMoney(2000);

/*int b = udi.insertUser(1, \夏翔\

if(b>0)

- 9 -

}

System.out.println(\成功!\

else }

System.out.println(\失败!\

package cn.jp.data; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; import javax.sql.DataSource; public final class Jdbc {

private static final String URL = \private static final String USERNAME = \private static final String PASSWORD = \private static Connection conn = null; private Jdbc() { } }

public static Connection getConn() {// 负责创建并返回数据库连接

- 10 -

static {// 负责加载数据库驱动 try {

System.out.println(\加载数据库驱动程序!\Class.forName(\

} catch (ClassNotFoundException e) { }

System.out.println(\在加载数据库驱动程序时抛出异常,内容如下:\e.printStackTrace();

}

if (conn == null) {// 数据库连接不存在 }

return conn;

try {

System.out.println(\创建数据库连接!\

conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);

} catch (SQLException e) { }

System.out.println(\在创建数据库连接时抛出异常,内容如下:\e.printStackTrace();

public static void free(ResultSet rs, Statement st, Connection conn) {

try {

if (rs != null)

rs.close();

} catch (SQLException e) {

e.printStackTrace();

} finally {

try {

if (st != null)

st.close();

} catch (SQLException e) {

e.printStackTrace();

} finally {

if (conn != null)

try {

conn.close();

} catch (Exception e) { }

- 11 -

e.printStackTrace();

}

}

}

}

package cn.jp.data; import java.util.Date; public class User { private long id; private String name; private Date birthday; private float money; public User() {

}

public long getId() { return id;

}

public void setId(long id) { this.id = id; }

public String getName() { return name; }

public void setName(String name) { this.name = name; }

public Date getBirthday() { return birthday; }

public void setBirthday(Date birthday) { this.birthday = birthday; }

public float getMoney() { return money;

}

public void setMoney(float money) { this.money = money; }

@Override

public String toString() { return \ + id + \ + name + \

+ \ + money ;

}

}

- 12 -

+ birthday

package cn.jp.data; import java.util.Date; public interface UserDao {

public int insertUser(int id,String username, int password,String birthday,float money) ; }

public void deleteUser(String username); public void findUser(String username);

public void updateUserPassword(String username,int password);

package cn.jp.data; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.Date;

public class UserDaoImpl implements UserDao {

} @Override

public UserDaoImpl() {

public int insertUser(int id, String username, int password,String birthday, float money) {

Connection conn = null; PreparedStatement pst = null; ResultSet rs = null; conn = Jdbc.getConn(); int data = 0;

Date d = convertDate(birthday); try {

pst = conn.prepareStatement(\pst.setInt(1, id);

pst.setString(2, username); pst.setInt(3, password);

- 13 -

}

pst.setDate(4,new java.sql.Date(d.getTime()));//????经典 pst.setFloat(5, money); data = pst.executeUpdate(); Jdbc.free(rs, pst, conn);

} catch (SQLException e) {

// TODO Auto-generated catch block e.printStackTrace();

}

return data;

@Override

public void deleteUser(String username) { } @Override

public void findUser(String username) {

// TODO Auto-generated method stub Connection conn = null;

- 14 -

Connection conn = null; PreparedStatement pst = null; ResultSet rs = null; conn = Jdbc.getConn(); try {

pst = conn.prepareStatement(\pst.setString(1, username); pst.executeUpdate(); Jdbc.free(rs, pst, conn);

} catch (SQLException e) {

// TODO Auto-generated catch block e.printStackTrace();

}

}

PreparedStatement pst = null; ResultSet rs = null; conn = Jdbc.getConn(); try {

pst = conn.prepareStatement(\pst.setString(1, username); rs = pst.executeQuery(); while(rs.next()){

System.out.println(rs.getString(1)+\

+rs.getString(3)+\

}

Jdbc.free(rs, pst, conn);

} catch (SQLException e) {

// TODO Auto-generated catch block e.printStackTrace();

}

@Override

public void updateUserPassword(String username, int password) { }

public Date convertDate(String strDate) {

String pat1 = \

SimpleDateFormat sdf1 = new SimpleDateFormat(pat1) ; Date d = null ; try{

d = sdf1.parse(strDate) ; // 将给定的字符串中的日期提取出来

// 如果提供的字符串格式有错误,则进行异常处理

// 实例化模板对象

// TODO Auto-generated method stub

}catch(Exception e){ }

e.printStackTrace() ; // 打印异常信息

- 15 -

}

}

return d;

实验九 Java GUI

1.实验目的

(1)了解Java图形用户界面开发步骤。 (2)掌握Java图形用户界面常用组件的使用。 (3)掌握Java图形用户界面事件处理。

(4)掌握WindowBuilder安装、swing及SWT组件的用法。

2.实验内容

实验题1 完成图9-1所示学籍管理主界面的设计与制作。

基本要求:如果输入用户名:admin,密码:123456,则弹出如图9-2所示窗口,否则弹出如图9-3所示窗口。

package L1;

import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel;

import javax.swing.border.EmptyBorder; import javax.swing.JLabel; import java.awt.Font;

import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JTextField; import javax.swing.JButton; import javax.swing.JPasswordField; public class test extends JFrame {

private JPanel contentPane; private JTextField textField; private JPasswordField passwordField; /**

- 16 -

* Launch the application. */

public static void main(String[] args) { } /**

* Create the frame. */

public test() {

setTitle(\登录\

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel();

contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JLabel name = new JLabel(\用户名\

name.setFont(new Font(\宋体\name.setBounds(118, 28, 62, 21); contentPane.add(name); textField = new JTextField();

textField.setFont(new Font(\宋体\textField.setBounds(180, 29, 122, 21);

- 17 -

EventQueue.invokeLater(new Runnable() { });

public void run() { }

try {

test frame = new test(); frame.setVisible(true);

} catch (Exception e) { }

e.printStackTrace();

contentPane.add(textField); textField.setColumns(10);

JLabel password = new JLabel(\密 码\

password.setFont(new Font(\宋体\password.setBounds(118, 72, 62, 21); contentPane.add(password);

JButton btnNewButton = new JButton(\登录\

btnNewButton.setFont(new Font(\宋体\btnNewButton.addActionListener(new ActionListener() { });

btnNewButton.setBounds(118, 130, 62, 23); contentPane.add(btnNewButton); JButton button = new JButton(\清空\

button.setFont(new Font(\宋体\button.addActionListener(new ActionListener() { });

- 18 -

public void actionPerformed(ActionEvent e) { }

String name = \String password = \

String str = new String(textField.getText()); String pw = new String(passwordField.getPassword()); if (str.equals(name) && (pw.equals(password))) { } else { }

JOptionPane.showMessageDialog(null, \登录失败!\

JOptionPane.showMessageDialog(null, \恭喜你,登录成功!!!\

public void actionPerformed(ActionEvent e) { }

textField.setText(\passwordField.setText(\

}

}

button.setBounds(240, 130, 62, 23); contentPane.add(button);

passwordField = new JPasswordField();

passwordField.setBounds(180, 73, 122, 21); contentPane.add(passwordField);

一道添加题:JButton button = new JButton(\添加\);

button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent arg0) {

for(int i = 0;i<2;i++){ }

Person p = new Person(textid.getText(),textname.getText()); //hs = new HashSet(); hs.add(p);

textname.setText(\); textid.setText(\);

}

一道显示题:JButton button_1 = new JButton(\显示\);

button_1.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent arg0) { }

Iterator it = hs.iterator(); StringBuilder sb = new StringBuilder(); while(it.hasNext())

textArea.setText(new String(sb));

sb.append(it.next());

});

实验题2 在文本框中输入目录,点击“转到”按钮,将该目录中的文件与文件夹名称列在下面的文本区域中,简单查询界面如图9-4所示。

- 19 -

图 9-4 文件列表

package L2;

import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel;

import javax.swing.border.EmptyBorder; import javax.swing.JLabel;

import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.JButton; import javax.swing.JTextArea;

import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.io.File; import java.awt.Font;

public class FileSeach extends JFrame {

private JPanel contentPane; private JTextField textField;

private JTextArea textArea = new JTextArea(); private JScrollPane scrollPane = new JScrollPane(); /**

* Launch the application. */

public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { FileSeach frame = new FileSeach(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /**

* Create the frame. */

- 20 -

public FileSeach() {

file1[i].getName()

setFont(new Font(\ setTitle(\文件列表\ setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JLabel lblNewLabel = new JLabel(\请输入目录\ lblNewLabel.setFont(new Font(\宋体\ lblNewLabel.setBounds(10, 20, 74, 22); contentPane.add(lblNewLabel); textField = new JTextField(); textField.setBounds(94, 20, 249, 22); contentPane.add(textField); JButton btnNewButton = new JButton(\转到\ btnNewButton.setFont(new Font(\宋体\ JLabel label = new JLabel(\目录下文件列表\ label.setFont(new Font(\宋体\ label.setBounds(10, 52, 101, 18); contentPane.add(label); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String path = textField.getText().trim(); File file = new File(path); File[] file1 = file.listFiles(); for (int i = 0; i < file1.length; i++) { // FileTA.append(file1[i].getName() + \ textArea.setText(textArea.getText() + \

textArea.setCaretPosition(textArea.getText().length()); } } }); btnNewButton.setBounds(353, 20, 63, 23); contentPane.add(btnNewButton); textField.setColumns(10); textArea.setLineWrap(true); textArea.setBounds(10, 49, 422, 203); scrollPane.setSize(422, 176); scrollPane.setLocation(10, 80); // contentPane.add(FileTA);

- 21 -

+

SCROLLBAR_ALWAYS); }

scrollPane.setHorizontalScrollBarPolicy(scrollPane.HORIZONTAL_ }

scrollPane.setViewportView(textArea); contentPane.add(scrollPane);

实验题3完成图9-5 所示图形界面的制作,基本要求:相关数据从数据库中读取。

package edu.cn.jp;

import java.beans.Statement; import java.sql.Connection; import java.sql.DriverManager;

import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class ConnectionJdbc {

static Connection conn = null; static { try {

Class.forName(\ } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } }

public static Connection getConnection() {

String url = \ String user = \ String password = \ try {

conn = DriverManager

.getConnection(url, user, password); } catch (SQLException e) {

// TODO Auto-generated catch block e.printStackTrace(); }

return conn;

- 22 -

}

public static void free(ResultSet rs, PreparedStatement pst, Connection conn) { try {

if (rs != null) rs.close();

} catch (SQLException e) { e.printStackTrace(); } finally { try {

if (pst != null)

((java.sql.Statement) pst).close(); } catch (SQLException e) { e.printStackTrace(); } finally {

if (conn != null) try {

conn.close();

} catch (SQLException e) { e.printStackTrace(); } } } } }

package edu.cn.jp;

import java.awt.BorderLayout; public class c extends JFrame { private JPanel contentPane; private JTextField bntf; private JTextField bnatf; private JTextField bptf; private JTextField betf; private JTextField bdtf; private JTextField bmtf; private JLabel labpicture;

private JFileChooser jfc = new JFileChooser(new File(\创建文件选择器 Connection conn = null;

PreparedStatement pst = null; ResultSet rst = null;

private JTextField pathTf; /**

* Launch the application. */

public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() {

- 23 -

try {

c frame = new c();

frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } });}

/* public boolean updatePic(String path,String eid)

{

boolean bFlag = true; try

{//创建预编译语句实现将图片存进数据库的功能 System.out.println(path); System.out.println(eid); PreparedStatement ps=conn.prepareStatement(\into book(Photo) values(?) where iD=?\

File f=new File(path);

int length=(int)f.length();//获取图片的长度

byte[] b=new byte[length];//创建byte数组其程度为图片文件的长度

FileInputStream fin=new FileInputStream(f);//创建文件类型字节流对象并为其指定源文件

fin.read(b);//读取文件存于byte数组中 fin.close();

ps.setBytes(1,b);//设置预编译语句中的字段的值 ps.setString(2, eid); bFlag = ps.execute();

System.out.println(bFlag); ps.close(); }

catch(Exception ei) {//捕获异常,并打印出来 ei.printStackTrace(); }

return bFlag; }*/

public ArrayList getPic(String id) {

ArrayList image = new ArrayList();// 定义照片向量 Image i = new ImageIcon(\ try {

conn = ConnectionJdbc.getConnection(); PreparedStatement pst = conn

.prepareStatement(\ pst.setString(1, bntf.getText()); rst = pst.executeQuery();

while (rst.next()) {// 当结果集不为空

- 24 -

byte[] buff = rst.getBytes(1);

if (buff != null) {// 当输入流不为空就将输入的照片显示 image.add((new ImageIcon(buff)).getImage()); }else {

image.add(i); } }

} catch (Exception e) {// 捕获异常,并打印出来 e.printStackTrace(); }

return image; } /**

* Create the frame. */

public c() {

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 482, 404); contentPane = new JPanel();

contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null);

JLabel lblNewLabel = new JLabel(\ lblNewLabel.setBounds(10, 21, 54, 15); contentPane.add(lblNewLabel);

JLabel lblNewLabel_1 = new JLabel(\ lblNewLabel_1.setBounds(10, 62, 54, 15); contentPane.add(lblNewLabel_1);

JLabel lblNewLabel_2 = new JLabel(\ lblNewLabel_2.setBounds(10, 104, 54, 15); contentPane.add(lblNewLabel_2);

JLabel lblNewLabel_3 = new JLabel(\ lblNewLabel_3.setBounds(10, 149, 54, 15); contentPane.add(lblNewLabel_3);

JLabel lblNewLabel_4 = new JLabel(\ lblNewLabel_4.setBounds(0, 203, 64, 21); contentPane.add(lblNewLabel_4);

JLabel lblNewLabel_5 = new JLabel(\ lblNewLabel_5.setBounds(10, 248, 54, 15); contentPane.add(lblNewLabel_5); bntf = new JTextField();

bntf.setBounds(77, 18, 129, 21); contentPane.add(bntf); bntf.setColumns(10);

bnatf = new JTextField();

bnatf.setBounds(77, 59, 129, 21);

- 25 -

contentPane.add(bnatf); bnatf.setColumns(10); bptf = new JTextField();

bptf.setBounds(77, 101, 129, 21); contentPane.add(bptf); bptf.setColumns(10); betf = new JTextField();

betf.setBounds(74, 146, 129, 21); contentPane.add(betf); betf.setColumns(10); bdtf = new JTextField();

bdtf.setBounds(77, 200, 129, 21); contentPane.add(bdtf); bdtf.setColumns(10); bmtf = new JTextField();

bmtf.setBounds(77, 245, 129, 21); contentPane.add(bmtf); bmtf.setColumns(10);

JButton btnNewButton = new JButton(\ btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (bntf.getText() == \

JOptionPane.showMessageDialog(null, \书号是不能为空的!\ return; } else { String sql = \into book(Id,Bname,Price,ISBN,PrintDate,Sales,Photo) values(?,?,?,?,?,?,?)\

conn = ConnectionJdbc.getConnection(); try {

pst = conn.prepareStatement(sql); pst.setString(1, bntf.getText()); pst.setString(2, bnatf.getText());

pst.setFloat(3, Float.parseFloat(bptf.getText())); pst.setString(4, bntf.getText());

pst.setDate(5, java.sql.Date.valueOf(bdtf.getText())); pst.setFloat(6, Float.parseFloat(bmtf.getText())); String path = pathTf.getText(); File f=new File(path);

int length=(int)f.length();//获取图片的长度

byte[] b=new byte[length];//创建byte数组其程度为图片文件的长度 FileInputStream fin; try {

fin = new FileInputStream(f); try {

fin.read(b); fin.close();

- 26 -

} catch (IOException e) {

// TODO Auto-generated catch block e.printStackTrace(); }//读取文件存于byte数组中

} catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace();

}//创建文件类型字节流对象并为其指定源文件 pst.setBytes(7,b);//设置预编译语句中的字段的 int count = pst.executeUpdate(); if (count != 0 ) {

JOptionPane.showMessageDialog(null, \插入成功!\ } else {

JOptionPane.showMessageDialog(null, \插入失败!\ }

ConnectionJdbc.free(rst, pst, conn); } catch (SQLException e) {

// TODO Auto-generated catch block e.printStackTrace(); } } } });

btnNewButton.setBounds(29, 307, 93, 23); contentPane.add(btnNewButton);

JButton btnNewButton_1 = new JButton(\btnNewButton_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (bntf.getText() == \

JOptionPane.showMessageDialog(null, \请输入书号!\ return; } else {

String sql = \ conn = ConnectionJdbc.getConnection(); try {

pst = conn.prepareStatement(sql); pst.setString(1, bntf.getText()); int count = 0;

count = pst.executeUpdate(); if (count != 0) {

JOptionPane.showMessageDialog(null, \删除成功!\ } else {

JOptionPane.showMessageDialog(null, \删除失败!\ }

ConnectionJdbc.free(rst, pst, conn); } catch (SQLException e) {

- 27 -

// TODO Auto-generated catch block e.printStackTrace(); } } } });

btnNewButton_1.setBounds(192, 307, 93, 23); contentPane.add(btnNewButton_1);

JButton btnNewButton_2 = new JButton(\ btnNewButton_2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (bntf.getText() == \

JOptionPane.showMessageDialog(null, \请输入书号!\ return; } else {

String sql = \where id = ?\

conn = ConnectionJdbc.getConnection(); try {

pst = conn.prepareStatement(sql); pst.setString(1, bntf.getText()); rst = pst.executeQuery(); while (rst.next()) {

bntf.setText(rst.getString(1)); bnatf.setText(rst.getString(2));

bptf.setText(String.valueOf(rst.getFloat(3))); betf.setText(rst.getString(4));

bdtf.setText(rst.getDate(5).toString());

bmtf.setText(String.valueOf(rst.getFloat(6))); ArrayList im = getPic(bntf.getText()); Image ima = im.get(0);

labpicture.setIcon(new ImageIcon(ima)); //将照片添加进照片标签 }

ConnectionJdbc.free(rst, pst, conn); } catch (SQLException e) {

// TODO Auto-generated catch block e.printStackTrace(); } } } });

btnNewButton_2.setBounds(345, 307, 93, 23); contentPane.add(btnNewButton_2);

JButton btnNewButton_3 = new JButton(\ btnNewButton_3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) {

- 28 -

}

}

if (bntf.getText() == \

JOptionPane.showMessageDialog(null, \请输入书号!\ return; } else {

pathTf.setText(\

jfc.showOpenDialog(contentPane);

if (jfc.getSelectedFile() != null) {

pathTf.setText(\ } } } });

btnNewButton_3.setBounds(321, 199, 93, 23); contentPane.add(btnNewButton_3);

JLabel labpicture = new JLabel(\labpicture.setBounds(266, 21, 155, 143); contentPane.add(labpicture);

pathTf = new JTextField();

pathTf.setBounds(293, 243, 159, 24); contentPane.add(pathTf); pathTf.setColumns(10);

JLabel lblNewLabe = new JLabel(\lblNewLabe.setBounds(238, 246, 72, 18); contentPane.add(lblNewLabe);

- 29 -

本文来源:https://www.bwwdw.com/article/4hmx.html

Top