解答例 - 実習課題1 - 2.バイナリファイルの入出力
(実習課題1)
以下のプログラムを作成しなさい。
- 任意のファイルを任意のファイルにコピーする。ファイルの指定はファイルダイアログで行う事。
- コピーは「FileInputStream」と「FileOutputStream」を用いて実現する事。
解答例
/**
* FilterCopyExample.java
* TECHSCORE Java 入出力2章 実習課題1
*
* Copyright (c) 2004 Four-Dimensional Data, Inc.
*/
package com.techscore.io.chapter2.exercise1;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class FileCopyExample extends JFrame implements ActionListener {
private JButton from = new JButton("コピー元");
private JButton to = new JButton("コピー先");
private JButton copy = new JButton("コピー実行");
private JLabel fromLabel = new JLabel("コピー元ファイル");
private JLabel toLabel = new JLabel("コピー先ファイル");
private JLabel copyLabel = new JLabel();
private JFileChooser chooser = new JFileChooser();
private File fromFile = null;
private File toFile = null;
//コンストラクタ
public FileCopyExample() {
super("ファイルのコピー");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 200);
getContentPane().setLayout(new GridLayout(6, 1));
getContentPane().add(from);
getContentPane().add(fromLabel);
getContentPane().add(to);
getContentPane().add(toLabel);
getContentPane().add(copy);
getContentPane().add(copyLabel);
from.addActionListener(this);
to.addActionListener(this);
copy.addActionListener(this);
}
public static void main(String[] args) {
new FileCopyExample().setVisible(true);
}
//ボタンが押されたときの処理
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(from)) {
setFromFile();
} else if (e.getSource().equals(to)) {
setToFile();
} else if (e.getSource().equals(copy)) {
copyFile();
}
}
//コピー先ファイルを設定するメソッド
private void setToFile() {
int returnVal = chooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
toFile = chooser.getSelectedFile();
toLabel.setText(toFile.getAbsolutePath());
}
}
//コピー元ファイルを設定するメソッド
private void setFromFile() {
int returnVal = chooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
fromFile = chooser.getSelectedFile();
fromLabel.setText(fromFile.getAbsolutePath());
}
}
//コピーを実行するメソッド
private void copyFile() {
try {
FileInputStream input = new FileInputStream(fromFile);
FileOutputStream output = new FileOutputStream(toFile);
byte buf[] = new byte[256];
int len;
while ((len = input.read(buf)) != -1) {
output.write(buf, 0, len);
}
output.flush();
output.close();
input.close();
copyLabel.setText("コピーされました");
} catch (FileNotFoundException e) {
copyLabel.setText("指定されたファイルが見つかりません");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

