자바

 

 

class FileExam

 

package java17_2;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.JScrollPane;

public class FileExam extends JFrame {

	private JPanel contentPane;
	private JTextField txtFileName;
	private JButton button;

	private JFileChooser jfc = new JFileChooser();
	private JButton btnSave;
	private JTextArea ta;
	
	
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					FileExam frame = new FileExam();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public FileExam() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 688, 471);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JLabel lblNewLabel = new JLabel("파일이름");
		lblNewLabel.setBounds(55, 59, 57, 15);
		contentPane.add(lblNewLabel);
		
		JButton btnOk = new JButton("파일정보");
		btnOk.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
//new File(파일 또는 디렉토리) : 파일의 정보를 가리키는 객체
				File file =new File(txtFileName.getText());								
				if(!file.exists()){			
					try{
						//file.createNewFile();//빈 파일을 생성
						file.mkdir();//디렉토리 생성
					}catch(Exception e2){
						e2.printStackTrace();
					}
				}	
				
				 String str ="파일이름:"+file.getName()+"\n"
						 +"파일크기:"+file.length()+"\n"
						 +"파일여부:"+file.isFile()+"\n"
						 +"파일종류:"+file.isFile() +"\n"
						 +"상위디렉토리:"+file.getParent();
				 	
				  ta.setText(str); //TextArea 내용 수정
				
			}
		});
		btnOk.setBounds(482, 55, 137, 23);
		contentPane.add(btnOk);
		
		txtFileName = new JTextField();
		txtFileName.setBounds(126, 56, 344, 21);
		contentPane.add(txtFileName);
		txtFileName.setColumns(10);
		
		JButton btnRead = new JButton("파일내용 읽기");
		btnRead.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//파일 이름
				String file=txtFileName.getText();
				String str="";
				BufferedReader reader=null;
				
				try{
				//new FileInputStream(파일객체) 파일의 내용을 읽는 객체
					reader =new BufferedReader(new InputStreamReader(new FileInputStream(file)));
					while(true){
						str =reader.readLine(); //한줄을 읽음
						if(str==null)break; //더이상 내용이 없으면 while 종료
						ta.append(str+"\n");//내용을 덧붙임
					}
					reader.close(); //BufferedReader 닫기
				}catch(Exception e2){
					e2.printStackTrace();
				}finally{ // 예외에 관계없이 항상 실행
					if(reader !=null){
						try{
							reader.close();
						}catch(IOException e1){
							e1.printStackTrace();
						}
					}
				}
			}
		});
		
		btnRead.setBounds(126, 87, 137, 23);
		contentPane.add(btnRead);
		
		button = new JButton("파일열기");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
			
				if(jfc.showOpenDialog(FileExam.this)== JFileChooser.APPROVE_OPTION){
						
						File file=new File(jfc.getSelectedFile().toString());
						
						if(!file.exists()){
							try {
								file.createNewFile();
							} catch (IOException e1) {
								e1.printStackTrace();
							}
						}
						
					  ta.setText("열기 경로 : " + jfc.getSelectedFile().toString() + "\n"); //TextArea 내용 수정	
					  ta.append("저장 경로 : " + jfc.getSelectedFile().toString()+"\n");
					  ta.append( jfc.getFileFilter().getDescription());
				}
			
			}
		});
		button.setBounds(482, 22, 137, 23);
		contentPane.add(button);
		
		//파일 저장 버튼
		btnSave = new JButton("파일내용저장");
		btnSave.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				BufferedWriter writer=null;
				try{
					String file=txtFileName.getText();//파일저장 위치 + 파일 이름
					// new FileWriter(파일) 파일에 문자 단위 기록
					writer=new BufferedWriter(new FileWriter(file));
					String str=ta.getText();
					writer.write(str);//파일 내용 저장
					
				}catch(Exception e2){
					e2.printStackTrace();
				}finally {
					try{
						if(writer!=null){
							writer.close(); // 버퍼 닫기
						}
					}catch(Exception e3){
						e3.printStackTrace();
					}
				}
			}
		});
		btnSave.setBounds(344, 87, 125, 23);
		contentPane.add(btnSave);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(44, 131, 575, 260);
		contentPane.add(scrollPane);
		
		ta = new JTextArea();
		scrollPane.setViewportView(ta);
	}
	
	
	
	
}





 

 

class StringExam

package java17_2;

//String : 불변성, final, 원본이 변경되지 않음.
//StringBuilder  : 원본이 변경됨
// 복잡한 문자열 연산 => StringBuilder 추천 
// "hello"
// str ==> "java"

public class StringExam {

	public static void main(String[] args) {
		//String str ="hello";
		String str =new String("hello");
		System.out.println(str);
		str ="java";
		System.out.println(str);
	//문자열.replace(A, B) A를 B로 변경
		System.out.println(str.replace("java", "jsp"));
		System.out.println(str);
	//StringBuilder  : 원본을 수정, 
		StringBuilder sb=new StringBuilder();
		
		sb.append("java");
		sb.append(" program");
		System.out.println(sb);
		sb.replace(0, 3, "jsp");
		System.out.println(sb);
		//java program
		//시작인덱스, 글자수, 문자열
		sb.replace(0, 4, "jsp");
		System.out.println(sb);
		String s2=sb.toString();
		
	}

	
}


 

class CopyFile1

package java17_2;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

//파일 내용을 읽어서 복사
// 파일 읽기 : InputStream => InputStreamReader
// 파일 쓰기 : OutputStream =>OutputStreamWriter
// FileInputStream => FileReader
// FileOutputStream => FileWriter
public class CopyFile1 {
	
	public static void main(String[] args) {
		FileInputStream in=null;
		FileOutputStream out=null;
		try{
//파일의 디렉토리 생략 => 현재 프로젝트의 루트 디렉토리
//디렉토리 구분자 : 윈도우  \, 리눅스 /				
			File file=new File("C:\\Users\\choi\\Desktop\\android_Image\\output1.txt");
			if(!file.exists()){
				file.createNewFile();
			}
			
			in =new FileInputStream(file);
			//자바 현재 디렉토리
			out=new FileOutputStream("output2.txt");
			int c;
//read() 1바이트를 읽어들임, 내용이 없으면 -1			
			while((c=in.read())!=-1){
				out.write(c);//output.txt 에 1바이트 기록
			}
			System.out.println("파일 복사 완료...");
			
		}catch (Exception e) {
			e.printStackTrace();
		}finally{// 예외 여부에 관계없이 항상 실행
			
			try{
				if(in!=null)in.close();
				if(out!=null)out.close();
				
			}catch(Exception e){
				e.printStackTrace();
			}
			
		}
	}
	
	
	
}


 

 

class ByteStreamLab

 

package java17_2;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Scanner;

//이미지 파일 복사
public class ByteStreamLab {

	public static void main(String[] args) {
		Scanner scan=new Scanner(System.in);
		System.out.println("원본 파일 이름을 입력하세요.");
		String inputFileName =scan.next();
		System.out.println("복사할 파일 이름을 입력하세요.");
		String outputFileName =scan.next();
		try(
			InputStream inputStream =new FileInputStream(inputFileName);
			OutputStream outputStream=new FileOutputStream(outputFileName);
			){
			int c;
//c=inputStream.read() 스트림에서 1바이트를 읽어서 c에 저장
// c != 1(내용이 없으면 -1)			
			while((c=inputStream.read())!=-1){
//파일에 저장				
				outputStream.write(c);
			}
			System.out.println("복사가 완료되었습니다.");
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	
}



 

class CharEncodingTest

package java17_2;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

//캐릭터셋(문자집합)
//자바의 기본 캐릭터셋(iso--8869-1, 서유럽언어)
//윈도우 : 기본 캐릭터셋(ms959, euc-kr)
//리눅스 : 기본 캐릭터셋(utf-8)

public class CharEncodingTest {
	
	public static void main(String[] args) {
		//파일 정보 참조 객체
		File fileDir =new File("C:\\Users\\choi\\Desktop\\android_Image\\k1.txt");
		BufferedReader in=null;
		try{
			in=new BufferedReader(new InputStreamReader(new FileInputStream(fileDir), "utf-8"));
			String str;
			//파일에서 한줄씩 읽어서 환면에 출력
			// str =in.readLine() 파일에서 한라인을 읽어서 str에 저장
			// str !=null
			while((str=in.readLine())!=null){
				System.out.println(str);
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try{
				if(in !=null){
					in.close();
				}
			}catch(Exception e2){
				e2.printStackTrace();
			}
		}
	}
	
	
}



 

 

 

 

 

about author

PHRASE

Level 60  머나먼나라

남도 그대만큼 할 수 있는 일이라면 하지를 말라. 남도 그대만큼 할 수 있는 말이라면 말하지 말라. 쓰는 것도 마찬가지다. 오직 그대 자신 속에 존재하는 것에 충실하라. 그렇게 함으로써 그대 자신을 없어서는 안 될 존재로 만들라. -앙드레 지드

댓글 ( 4)

댓글 남기기

작성