본문 바로가기

java

심화 예제 (Quiz Step13~16)

 

 

Quiz1

Scanner 객체를 이용해서 문자열 한줄을 입력 받은 다음
c:/acorn202206/myFolder/quiz.txt 파일을 만들어서
해당 파일에 문자열을 저장해 보세요

 

Quiz1Me(필자 작업)

package test.main;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class Quiz1Me {
	public static void main(String[] args) {
		Scanner scan=new Scanner(System.in);
		String scanline=scan.nextLine();
		File memoFile=new File("c:/acorn202206/myFolder/quiz.txt");
		try {
			if(!memoFile.exists()) {
				memoFile.createNewFile();
			}
			FileWriter fw=new FileWriter(memoFile, true);
			fw.write(scanline);
			fw.flush();
			fw.close();
			System.out.println("문자열을 저장");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

 

Quiz01 (모범 답안)

package test.main;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class Quiz01 {
   public static void main(String[] args) {
      File f = new File("C:/acorn202206/myFolder/quiz.txt");
      
      Scanner sc = new Scanner(System.in);
      
      System.out.print("문자열 입력 : ");
      String text = sc.nextLine();
      
      FileWriter writer = null;
      BufferedWriter bw = null;
      try {
         if(!f.exists()) {
            f.createNewFile();
         }
         writer = new FileWriter(f, true);
         bw = new BufferedWriter(writer);
         bw.write(text);
         bw.flush();
      } catch(IOException e) {
         e.printStackTrace();
      } finally {
         try {
            if(bw!=null) bw.close();
            if(writer!=null) writer.close();
         } catch(IOException e) {
            e.printStackTrace();
         }
      }
   }
}

 


Quiz2

 

JTextField에 문자열을 입력하고 추가버튼을 누르면
입력한 문자열이 c:/acorn202206/myFolder/memo.txt 파일에 append 되도록 해보세요.

불러오기 버튼을 누르면 c:/acorn202206/myFolder/memo.txt 파일에 있는 모든 문자열을
JTextArea에 출력하도록 해보세요.

 

Quiz2Me (필자 작업)

package test.main;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class Quiz2Me extends JFrame implements ActionListener {
	JTextField inputMsg;
	JTextArea outputMsg;
	//생성자
	public Quiz2Me(String title) {
		super(title);
		setLayout(new FlowLayout());
		JButton btn1=new JButton("추가하기");
		inputMsg=new JTextField(10);
		JButton btn2=new JButton("불러오기");
		outputMsg=new JTextArea();


		add(btn1);
		add(inputMsg);
		add(btn2);
		add(outputMsg);
		
		btn1.addActionListener(this);
		btn2.addActionListener(this);
	}
	
	public static void main(String[] args) {
	      JFrame f=new Quiz2Me("Quiz2");
	      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	      f.setBounds(100,  100, 500, 500);
	      f.setVisible(true);
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		String command=e.getActionCommand();
		File memoFile=new File("c:/acorn202206/myFolder/memo.txt");
		FileReader fr=null;
	    BufferedReader br=null;
	    
	    if(command.equals("추가하기")) {
	    	String msg=inputMsg.getText();
	    	try {
				FileWriter fw=new FileWriter(memoFile, true);
				fw.write(msg);
				fw.flush();
				fw.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
	    }else if(command.equals("불러오기")) {
	    	try {
	            //파일에서 문자열을 읽어들일수 있는 객체 생성
	            fr=new FileReader(memoFile);
	            br=new BufferedReader(fr);
	            while(true) {
	               //문자열 한줄 읽어내기 
	               String line=br.readLine();//개행 기호는 읽어내지 않는다 
	               //더이상 읽을 데이터가 없으면 반복문 탈출
	               if(line==null) {
	                  break;
	               }
	               outputMsg.append(line);
	            }
	            
	         } catch (FileNotFoundException fe) {
	            fe.printStackTrace();
	         } catch (IOException ie) {
	            ie.printStackTrace();
	         }finally { //예외가 발생 하던 안하던 실행이 반드시 보장되는 블럭
	       	  //예외가 발생한다면 try catch 블럭으로 묶어 준다.
	            try {
	           	 //NullpointerException 을 방지하면서 마무리 작업을 한다.
	               if(br!=null)br.close();
	               if(fr!=null)fr.close();
	            } catch (IOException ioe) {
	               ioe.printStackTrace();
	            }
	         }
	    }
	}
}

 

Quiz02 (모범 답안)

package test.main;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class Quiz02 extends JFrame implements ActionListener {
   JTextField tf;
   JTextArea ta;
   
   public Quiz02(String title) {
      super(title);
      setLayout(new BorderLayout());
      //페널
      JPanel jp=new JPanel();
      tf=new JTextField(10);
      JButton appendBtn=new JButton("추가");
      JButton printBtn=new JButton("불러오기");
      ta =new JTextArea();
      //스크롤바를 만들어주는 객체 
      JScrollPane jsp = new JScrollPane(ta);
      
      //페널의 배경색을 오랜지색으로 
      jp.setBackground(Color.ORANGE);
      //페널을 프레임의 북쪽에 배치 
      add(jp, BorderLayout.NORTH);
      //페널에 JTextField, JButton 2 개를 배치 
      jp.add(tf);
      jp.add(appendBtn);
      jp.add(printBtn);
      //JTextArea 를 포함하고 있는 JScrollPane 을 프레임의 가운데에 추가하기 
      add(jsp, BorderLayout.CENTER);
        
      appendBtn.addActionListener(this);
      printBtn.addActionListener(this);
   }
   
   public static void main(String[] args) {
      JFrame frame=new Quiz02("문자열 추가");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setBounds(100,100,500,500);
      frame.setVisible(true);
   }

   @Override
   public void actionPerformed(ActionEvent e) {
      File memoFile=new File("c:/acorn202206/myFolder/memo.txt");
      
      if(e.getActionCommand().equals("추가")) {
        //입력한 문자열을 읽어와서 
         String text=tf.getText();
         FileWriter fw=null;

         try {
            if(!memoFile.exists()) {
               JOptionPane.showConfirmDialog(this, "메모장을 만듭니다.");
               memoFile.createNewFile();
            }
            fw=new FileWriter(memoFile,true);
            //개행기호와 함께 파일에 출력하고 
            fw.write(text+"\r\n");
            fw.flush();
            //입력창 clear 
            tf.setText("");
            
         } catch (FileNotFoundException e1) {
            e1.printStackTrace();
         } catch (IOException e1) {
            e1.printStackTrace();
         }finally {
            try {
               if(fw!=null)fw.close();
            } catch (IOException e1) {
               e1.printStackTrace();
            }
         }
      }else {
         ta.setText("");
         FileReader fr=null;
         BufferedReader br=null;
         if(!memoFile.exists()) {
            JOptionPane.showConfirmDialog(this, "불러올 메모장이 없습니다.");
         }else {
            try {
               fr=new FileReader(memoFile);
               br=new BufferedReader(fr);
               //반복문 돌면서 
               while(true) {
                  //한줄씩 읽어내기 
                  String line=br.readLine();
                  //만일 다 읽었다면
                  if(line==null) {
                     break; //반복문 탈출
                  }
                  //JTextArea 에 읽은 내용을 개행기호와 함께 출력하기 
                  ta.append(line+"\n");
               }
            } catch (FileNotFoundException e1) {
               e1.printStackTrace();
            } catch (IOException e1) {
               e1.printStackTrace();
            }finally {
               try {
                  if(br!=null)br.close();
                  if(fr!=null)fr.close();
               } catch (IOException e1) {
                  e1.printStackTrace();
               }
            }
         }
      }
   }
}