DataInputStream
과DataOutputStream
은 자바의 기본 자료형 데이터를 바이트 스트림으로 입출력하는 기능을 제공하는 ByteStream 클래스이다.
FileInputStream
/FileOutputStream
과의 차이점은 자바 기본 자료형 데이터를 입/출력 할 수 있다는 것
FileInputStream
/FileOutputStream
은 byte단위의 데이터만 입/출력을 할 수 있었다.
하지만DataStream Filter
를 적용함으로써,
자바 기본 자료형(char, int, long, ...) 으로 데이터를 입력하고 출력할 수 있다.
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class IOEx1 {
// 쓰는거 save, 보기 편하려고 만듬
public static void write() {
FileOutputStream fos = null;
DataOutputStream dos = null;
try {
// result.dat 파일을 출력하는 객체를 생성
fos = new FileOutputStream("result.dat");
// DataOutputStream Filter를 적용한다.
dos = new DataOutputStream(fos);
// result.dat 파일에 각 기본형 데이터를 출력한다.
dos.writeInt(500);
dos.writeDouble(3.14);
dos.writeBoolean(true);
dos.writeUTF("이것은 한글");
// 하나 더 쓰면 줄 바뀜!
dos.writeUTF("이제 하루만 더 버티면 나는 자유다~ \n 안녕! ");
dos.flush();
} catch(IOException e) {
e.printStackTrace();
} finally {
IOUtil.closeAll(dos, fos); // 자원해제 필수!
}
}
public static void read() {
FileInputStream fis = null;
DataInputStream dis = null;
try {
// "result.dat" 파일을 읽는 객체를 생성함
fis = new FileInputStream("result.dat");
// DataInputStream Filter를 적용한다.
dis = new DataInputStream(fis);
// "result.dat" 파일에서 각 기본형 데이터를 읽어 옴
int num = dis.readInt();
double pi = dis.readDouble();
boolean flag = dis.readBoolean();
String str1 = dis.readUTF();
String str2 = dis.readUTF();
// 반대로 읽어옴!
System.out.println(num);
System.out.println(pi);
System.out.println(flag);
System.out.println(str1);
System.out.println(str2);
} catch(IOException e) {
e.printStackTrace();
} finally {
IOUtil.closeAll(dis, fis); // 자원해제 필수!
}
}
public static void main(String[] args) {
//write();
read();
}
}
FileOutputStream
으로 "result.dat" 파일에 스트림 객체를 생성하고
DataOutputStream
을 Filter로 적용하여, 자바 기본형 타입들로 파일에 데이터를 출력한다.FileInputStream
으로 "result.dat" 파일에 스트림 객체를 생성하고
DataInputStream
을 Filter로 적용하여, 자바 기본형 타입들로 파일의 데이터를 가져온다.
package kr.ac.green;
public class Some {
private int intValue;
private String strValue;
private double doubleValue;
// alt + shift + s -> c
public Some() { }
// alt + shift + s -> o
public Some(int intValue, String strValue, double doubleValue) {
super();
this.intValue = intValue;
this.strValue = strValue;
this.doubleValue = doubleValue;
}
// alt + shift + s -> r
public int getIntValue() {
return intValue;
}
public void setIntValue(int intValue) {
this.intValue = intValue;
}
public String getStrValue() {
return strValue;
}
public void setStrValue(String strValue) {
this.strValue = strValue;
}
public double getDoubleValue() {
return doubleValue;
}
public void setDoubleValue(double doubleValue) {
this.doubleValue = doubleValue;
}
// alt + shift + s -> s
@Override
public String toString() {
return "Some [intValue=" + intValue + ", strValue=" + strValue + ", doubleValue=" + doubleValue + "]";
}
}
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class IOEx2 {
public static void write() {
Some[] arr = {
new Some(3,"아 하기싫다", 0.88),
new Some(1,"하늘엔 조각구름 떠있고", 0.88),
new Some(100,"강물엔 유람선이 떠있고", 0.88),
new Some(7,"저마다 누려야 할 행복에", 0.88),
new Some(20,"언제나 자유로운 곳", 0.88),
new Some(6,"아 아 대한민국 아 아 우리조국", 0.88)
};
// 사용하려면
FileOutputStream fos = null;
DataOutputStream dos = null;
try {
fos = new FileOutputStream("some.dat");
dos = new DataOutputStream(fos);
for(Some temp : arr) {
dos.writeInt(temp.getIntValue());
dos.writeUTF(temp.getStrValue());
dos.writeDouble(temp.getDoubleValue());
}
dos.flush();
} catch(IOException e) {
e.printStackTrace();
} finally {
IOUtil.closeAll(dos, fos); // 자원해제 필수!
}
}
public static void read() {
FileInputStream fis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream("some.dat");
dis = new DataInputStream(fis);
while(dis.available() > 0) {
Some s = new Some(
dis.readInt(),
dis.readUTF(),
dis.readDouble()
);
System.out.println(s);
}
} catch(IOException e) {
e.printStackTrace();
} finally {
IOUtil.closeAll(dis, fis); // 자원해제 필수!
}
}
public static void main(String[] args) {
//write();
read();
}
}
Map
File
로 읽고 (load)
, 저장 (Store)
하는 메서드들을 제공하므로key / Value
구분해서 알아서 써줌Properties
는 Hashtable
을 상속받아 구현되어있음Hashtable
은 HashMap
의 Old Version이라고 생각하면 됨!Properties
는 Hashtable
을 상속 받았기 때문에 Map의 특성을 가지고 있음Hashtable
은 Key-Value를 Object Type
로 저장하지만Properties
는 Key-Value를 String Type
으로 저장합니다.import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class IOEx3 {
//설정파일 만들 때
public static void write() {
Properties prop = new Properties();
// 형변환을 보장, 사이즈가 4,
// put 대신에 setProperty 를 사용!
// 어떻게 구분할지 생각 안해도 됨
prop.setProperty("first", "1stValue");
prop.setProperty("second", "2ndValue");
prop.setProperty("third", "3rdValue");
prop.setProperty("fourth", "4thValue");
FileOutputStream fos = null;
try {
fos = new FileOutputStream("mysettings.properties");
prop.store(fos, "made in korea");
// fos = new FileOutputStream("mysettings.xml");
// prop.storeToXML(fos, "made in busan");
} catch(IOException e) {
e.printStackTrace();
} finally {
IOUtil.closeAll(fos);
}
}
public static void main(String[] args) {
write();
}
}
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class IOEx3 {
//설정파일 만들 때
public static void write() {
Properties prop = new Properties();
// 형변환을 보장, 사이즈가 4,
// put 대신에 setProperty 를 사용!
// 어떻게 구분할지 생각 안해도 됨
prop.setProperty("first", "1stValue");
prop.setProperty("second", "2ndValue");
prop.setProperty("third", "3rdValue");
prop.setProperty("fourth", "4thValue");
FileOutputStream fos = null;
try {
// fos = new FileOutputStream("mysettings.properties");
// prop.store(fos, "made in korea");
fos = new FileOutputStream("mysettings.xml");
prop.storeToXML(fos, "made in busan");
} catch(IOException e) {
e.printStackTrace();
} finally {
IOUtil.closeAll(fos);
}
}
public static void main(String[] args) {
write();
}
}
Map은 순서정렬이 안되기때문에 뒤죽박죽으로 나옴!
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class IOEx3 {
//설정파일 만들 때
public static void write() {
Properties prop = new Properties();
// 형변환을 보장, 사이즈가 4,
// put 대신에 setProperty 를 사용!
// 어떻게 구분할지 생각 안해도 됨
prop.setProperty("first", "1stValue");
prop.setProperty("second", "2ndValue");
prop.setProperty("third", "3rdValue");
prop.setProperty("fourth", "4thValue");
FileOutputStream fos = null;
try {
//// fos = new FileOutputStream("mysettings.properties");
//// prop.store(fos, "made in korea");
fos = new FileOutputStream("mysettings.xml");
prop.storeToXML(fos, "made in busan");
} catch(IOException e) {
e.printStackTrace();
} finally {
IOUtil.closeAll(fos);
}
}
public static void read() {
FileInputStream fis = null;
try {
Properties prop = new Properties();
// fis = new FileInputStream("mysettings.properties");
// prop.load(fis);
fis = new FileInputStream("mysettings.xml");
prop.loadFromXML(fis);
System.out.println(prop);
} catch(IOException e) {
e.printStackTrace();
} finally {
IOUtil.closeAll(fis);
}
}
public static void main(String[] args) {
//write();
read();
}
}
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
public class MyFrame extends JFrame {
private JLabel lblText;
private Properties prop = new Properties();
private JMenuBar mBar;
private JMenu mSettings;
private JMenuItem miProperties;
public MyFrame() {
FileInputStream fis = null;
try {
fis = new FileInputStream("myframe.properties");
prop.load(fis);
} catch(IOException e) {
e.printStackTrace();
} finally {
IOUtil.closeAll(fis);
}
mBar = new JMenuBar();
mSettings = new JMenu("settings");
miProperties = new JMenuItem("set properties");
mSettings.add(miProperties);
mBar.add(mSettings);
setJMenuBar(mBar);
miProperties.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
new SettingDlg(MyFrame.this);
}
});
lblText = new JLabel(prop.getProperty("myframe.text"), JLabel.CENTER);
add(lblText, BorderLayout.CENTER);
setTitle(prop.getProperty("myframe.title"));
setSize(getIntValue("myframe.width"), getIntValue("myframe.height"));
setLocation(getIntValue("myframe.x"), getIntValue("myframe.y"));
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
private int getIntValue(String key) {
return Integer.parseInt(prop.getProperty(key));
}
public void setValue(String key, String value) {
prop.setProperty(key, value);
}
public String getValue(String key) {
return prop.getProperty(key);
}
public String[] getKeys() {
return prop.keySet().toArray(new String[0]);
}
public void save() {
FileOutputStream fos = null;
try {
fos = new FileOutputStream("myframe.properties");
prop.store(fos, "from GUI");
JOptionPane.showMessageDialog(
this,
"변경된 내용은 다시 실행하면 적용됩니다.",
"알림",
JOptionPane.INFORMATION_MESSAGE
);
} catch(IOException e) {
JOptionPane.showMessageDialog(
this,
"저장중 문제가 발생했습니다. 잠시후 시도하세요",
"에러",
JOptionPane.ERROR_MESSAGE
);
} finally {
IOUtil.closeAll(fos);
}
}
public static void main(String[] args) {
new MyFrame();
}
}
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class SettingDlg extends JDialog {
private MyFrame owner;
private InputPanel[] pnls;
private JButton btnSave;
private JButton btnClose;
public SettingDlg(MyFrame owner) {
super(owner, "settings", true);
this.owner = owner;
String[] info = owner.getKeys();
pnls = new InputPanel[info.length];
for(int i=0; i<pnls.length; i++) {
pnls[i] = new InputPanel(info[i]);
}
JPanel pnlCenter = new JPanel(new GridLayout(0, 1));
for(InputPanel temp : pnls) {
pnlCenter.add(temp);
}
btnSave = new JButton("save");
btnClose = new JButton("close");
JPanel pnlSouth = new JPanel(new GridLayout(1, 2));
pnlSouth.add(btnSave);
pnlSouth.add(btnClose);
add(pnlCenter, BorderLayout.CENTER);
add(pnlSouth, BorderLayout.SOUTH);
ActionListener aListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
Object src = ae.getSource();
if(src == btnSave) {
for(InputPanel temp : pnls) {
owner.setValue(temp.getName(), temp.getValue());
}
owner.save();
}
dispose();
}
};
btnSave.addActionListener(aListener);
btnClose.addActionListener(aListener);
setTitle("settings");
pack();
setLocationRelativeTo(owner);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setVisible(true);
}
private class InputPanel extends JPanel {
private JLabel lbl;
private JTextField tfInput;
private String name;
private InputPanel(String text) {
this.name = text;
lbl = new JLabel(text, JLabel.LEFT);
lbl.setPreferredSize(new Dimension(150, 20));
tfInput = new JTextField(20);
tfInput.setText(owner.getValue(text));
add(lbl);
add(tfInput);
}
public String getName() {
return name;
}
public String getValue() {
return tfInput.getText();
}
}
}
#myframe.properties
#myframe.properties myframe.width=700 myframe.height=200 myframe.x=500 myframe.y=300 myframe.title=this is a new Title myframe.text=all new frame