Потоки та робота із файлами у Java

Інформація про навчальний заклад

ВУЗ:
Національний університет Львівська політехніка
Інститут:
О
Факультет:
КН
Кафедра:
Не вказано

Інформація про роботу

Рік:
2016
Тип роботи:
Інші
Предмет:
ОБД

Частина тексту файла (без зображень, графіків і формул):

МІНІСТЕРСТВО ОСВІТИ ТА НАУКИ УКРАЇНИ НАЦІОНАЛЬНИЙ УНІВЕРСИТЕТ “ЛЬВІВСЬКА ПОЛІТЕХНІКА”  Потоки та робота із файлами у Java 1. МЕТА РОБОТИ Одержати навики роботи з потоками в Java. 2.ЛАБОРАТОРНЕ ЗАВДАННЯ Створити програму копіювання файлу з одного каталога в іншій. Компоненти графічного вікна: напис "Копіювання файлу" у області North, розщеплена панель у області Center і кнопка "Копіювати" у області South. У лівій частині розщепленої панелі розміщений об'єкт класу JFileChooser для вибору файлу копіювання, а в правій частині - інший об'єкт класу JFileChooser, в якому вибирається каталог для копіювання. Копіювання файлу виконується при натисненні кнопки. 3.КОД ПРОГРАМИ package com.copyFile.test; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.*; import javax.swing.*; import javax.swing.border.Border; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; public class CopyGUI extends JFrame implements ActionListener, ChangeListener { private JLabel fromLabel; private JLabel toLabel; private JTextField fromField; private JTextField toField; private JButton fromButton; private JButton toButton; private JProgressBar progressBar; private JButton beginButton; private File fromFile; private File toFile; private long fileLength; private String fileName; public CopyGUI() { try { init(); } catch(Exception ex) { } } private void init() throws ClassNotFoundException, UnsupportedLookAndFeelException, InstantiationException, IllegalAccessException { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); setDefaultCloseOperation(DISPOSE_ON_CLOSE); setBounds(200, 200, 400, 300); setResizable(false); setTitle("File Copy"); JPanel panel = new JPanel(null); panel.setBackground(new Color(79, 199, 238)); add(panel); Border borderForButton = BorderFactory.createLineBorder(Color.white, 1); Border border = BorderFactory.createLineBorder(Color.white, 1); fromLabel = new JLabel("From:"); fromLabel.setBounds(40, 20, 50, 20); fromLabel.setForeground(Color.white); fromField = new JTextField(); fromField.setBounds(100, 20, 200, 20); fromButton = new JButton("Browse"); fromButton.setBounds(300, 20, 80, 20); fromButton.addActionListener(this); fromButton.setContentAreaFilled(false); fromButton.setForeground(Color.WHITE); fromButton.setBorder(borderForButton); toLabel = new JLabel("To: "); toLabel.setBounds(40, 40, 50, 20); toLabel.setForeground(Color.white); toField = new JTextField(); toField.setBounds(100, 40, 200, 20); toButton = new JButton("Browse"); toButton.setBounds(300, 40, 80, 20); toButton.addActionListener(this); toButton.setContentAreaFilled(false); toButton.setForeground(Color.WHITE); toButton.setBorder(borderForButton); panel.add(fromLabel); panel.add(fromField); panel.add(fromButton); panel.add(toLabel); panel.add(toField); panel.add(toButton); progressBar = new JProgressBar(); progressBar.setBounds(50, 100, 300, 30); progressBar.addChangeListener(this); progressBar.setBorder(border); panel.add(progressBar); beginButton = new JButton("Copy"); beginButton.setBounds(50, 130, 300, 70); beginButton.setForeground(Color.WHITE); beginButton.setFont(new Font("Verdana", Font.BOLD, 20)); beginButton.setBorder(borderForButton); beginButton.setContentAreaFilled(false); beginButton.addActionListener(this); panel.add(beginButton); } public void actionPerformed(ActionEvent e) { /* * choose from file */ if (e.getSource() == fromButton) { JFileChooser fileChooser = new JFileChooser(); fileChooser.setMultiSelectionEnabled(false); fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); int op = fileChooser.showOpenDialog(this); if (op == JFileChooser.APPROVE_OPTION) { fromFile = fileChooser.getSelectedFile(); fileName = fromFile.getName(); fromField.setText(fromFile.getAbsolutePath()); } } /* * choose to file */ if (e.getSource() == toButton) { JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int op = fileChooser.showOpenDialog(this); if (op == JFileChooser.APPROVE_OPTION) { toFile = fileChooser.getSelectedFile(); if (fileName != null) { fileName = fromFile.getName(); } toField.setText(toFile.getAbsolutePath() + fileName); } } /* * begin copy method */ if (e.getSource() == beginButton) { /* * before copy check from file and to file */ if ("".equals(fromField.getText())) { JOptionPane.showMessageDialog(this, "Please choose file to copy!"); return; } if ("".equals(toField.getText())) { JOptionPane.showMessageDialog(this, "Please choose directory to copy!"); return; } /* * get copy from file and to file */ fromFile = new File(fromField.getText()); toFile = new File(toField.getText()); /* * if to file exist, ask user information */ if (toFile.exists()) { int op = JOptionPane.showConfirmDialog(this, toFile.getName() + " File already exist! \n Do your want to cover it?", "Confirm Window", JOptionPane.YES_NO_OPTION); if (op == JOptionPane.NO_OPTION) { JOptionPane.showMessageDialog(this, "Copy Canceled"); fromField.setText(""); toField.setText(""); return; } } /* * get file length, set progressBar max value */ fileLength = fromFile.length(); progressBar.setMaximum((int) fileLength); /* * copy method add to a new thread when copying, increase progress * bar */ Runnable r1 = new Runnable() { public void run() { try { FileInputStream fis = new FileInputStream(fromFile); FileOutputStream fos = new FileOutputStream(toFile); byte[] buf = new byte[2048]; int size = 0; int flag = 0; while ((size = fis.read(buf)) != -1) { fos.write(buf, 0, size); flag += size; progressBar.setValue(flag); } fis.close(); fos.close(); } catch (Exception e1) { e1.printStackTrace(); } } }; /* * start new thread */ Thread t1 = new Thread(r1); t1.start(); } } /* * update progress bar value */ public void stateChanged(ChangeEvent e) { if (e.getSource() == progressBar) { if (progressBar.getValue() == progressBar.getMaximum()) { JOptionPane.showMessageDialog(this, "Copying Done"); progressBar.setValue(0); } } } /* * Main method */ public static void main(String[] args) { new CopyGUI().setVisible(true); } РЕЗУЛЬТАТИ ВИКОНАННЯ ВИСНОВОК На даній лабораторній роботі я навчився працювати з потоками вводу/виводу у мові програмування Java . Виконав індивідуальне завдання.
Антиботан аватар за замовчуванням

23.05.2016 19:40

Коментарі

Ви не можете залишити коментар. Для цього, будь ласка, увійдіть або зареєструйтесь.

Ділись своїми роботами та отримуй миттєві бонуси!

Нічого не вибрано
0%

Оголошення від адміністратора

Антиботан аватар за замовчуванням

Подякувати Студентському архіву довільною сумою

Admin

26.02.2023 12:38

Дякуємо, що користуєтесь нашим архівом!