[JAVA]Map,hashmap,ListTest,properties,I/O 개념정리와 적용예제

Devel/JAVA|2020. 8. 16. 17:59
반응형
-Map


keymap
"one"객체
"test"객체
"test1"객체



person이면 person객체
String-> String


-hashmap

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

public class MapTest {

    public static void main(String[] args) {
        HashMap<String,Person> map = new HashMap<>();
        map.put("one", new Person("홍길동",20,"서울"));
        map.put("two", new Person("이순신",30,"전라"));
        map.put("three", new Person("유관순",40,"서울"));
        
        //get(key)
        System.out.println(map.get("one").getName());
        Person one = map.get("one");
        System.out.println(one.getName());
        
        Set<String>keys = map.keySet();
        for(String key : keys) {
            Person p = map.get(key);
            System.out.println(p.getName());
            //System.out.println(key+ "="+ map.get(key).getName());
        }
        
        Iterator<String> ite = keys.iterator();
        while(ite.hasNext()) {            
            String key = ite.next();
            Person p = map.get(key);
            System.out.println(key+ "="+p.getName());
            //System.out.println(key +map.get(key).getName());
        }
    }

}

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

public class MapTest2 {

    public static void main(String[] args) {
        ArrayList<Person> list1 = new ArrayList<Person>();
        list1.add(new Person("홍길동",20,"서울"));
        list1.add(new Person("홍길동2",30,"서울2"));
        list1.add(new Person("홍길동3",40,"서울3"));
        
        ArrayList<Person> list2 = new ArrayList<Person>();
        list1.add(new Person("이순신",20,"전라"));
        list1.add(new Person("이순신2",30,"전라2"));
        list1.add(new Person("이순신3",40,"전라3"));

        HashMap<String, ArrayList<Person>> map =
                new HashMap<String, ArrayList<Person>>();
        map.put("one", list1);
        map.put("two", list2);
        
        
        Set<String>keys = map.keySet();        
        for(String key : keys) {
            ArrayList<Person>xxx = map.get(key);
            for(Person p : xxx) {
                System.out.println(p.getName()+"\t"+p.getAge());
            }
        }
    }

}

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class MapTest3 {

    public static void main(String[] args) {
        Map<String,Integer> map = new HashMap<String,Integer>();
        map.put("m1", 1);
        map.put("m2", 2);
        map.put("m3", 3);
        map.put("m4", 4);
        map.put("m5", 5);
        map.put("m6", 6);
        map.put("m7", 7);
        map.put("m8", 8);
        map.put("m9", 9);
        map.put("m10", 10);
        int sum=0;
        int sum1=0;
        
//        for(int i=1;i<=10;i++) {
//            map.put(i+"", i);
//        }
        Set<String>keys = map.keySet();
        for(String key : keys) {            
            sum+=map.get(key);            
        }System.out.println(sum);
        
        Iterator<String> ite = keys.iterator();
        while(ite.hasNext()) {
            String key = ite.next();
            sum1+=map.get(key);
        }System.out.println(sum1);

    }

}


import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

public class MapTest4 {

    public static void main(String[] args) {
        HashMap<String,Person> map = new HashMap<>();
        map.put("one",new Person("홍길동",20,"서울"));
        map.put("two",new Person("이순신",30,"전라"));
        map.put("three",new Person("유관순",40,"서울"));
        
        HashMap<String,Person> map2 = new HashMap<>();
        map2.put("one",new Person("홍길동2",20,"서울2"));
        map2.put("two",new Person("이순신2",30,"전라2"));
        map2.put("three",new Person("유관순2",40,"서울"));
        
        ArrayList<HashMap<String,Person>> list = new ArrayList<HashMap<String,Person>>();
        list.add(map);
        list.add(map2);
        
        
        for(HashMap<String,Person> x : list) {
            Set<String>keys = x.keySet();            
        for(String key : keys) {
            Person p = x.get(key);
            System.out.println(p.getName());
        }
        
    }
    
    }}

**
ListTest

import java.util.ArrayList;
public class ListTest03 {
public static void main(String[] args) {       
        RandomService test= new RandomService();
            test.makeRandomInt();
            test.printArrayList();
            //리스트를 받아서 메인에서 쓰고 싶다면, map을 하거나, getlist1, get list2를 만들거나
            
//          list1 = test.makeRandomInt(list1);
//          list2 = test.makeRandomInt(list2);
       // test.printArrayList(list1,list2);
               }
}


import java.util.ArrayList;
public class RandomService {
       ArrayList<Integer> list1 ;
       ArrayList<Integer> list2  ;
      
      
       public RandomService() {
             super();
             list1 = new ArrayList<Integer>();
             list2 = new ArrayList<Integer>();
       }
      public void makeRandomInt() {
            
             for(int i = 0 ; i < 10; i++) {
                  
                  list1.add((int) (Math.random() * 10));                             
                  list2.add((int) (Math.random() * 10));            
                        
              }
            
                  
      }
      public void printArrayList() {
             for(int i = 0; i < 10; i++) {
                
                 
                  try {
                      System.out.print(list1.get(i) + "/" + list2.get(i) + " ");
                      System.out.println(list1.get(i) / list2.get(i));
                     
                  } catch (Exception e) {
                      System.out.println("분모가 0입니다");
                  }
             }
      }
      
      
}

-Hashtable


-properties




-I/O




import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class Ex11_9 {
      public static void main(String[] args) {
      System.out.println("데이터를 입력하시오");
      BufferedReader buffer = null;
      PrintWriter out = null;
      try {
            File f = new File("c:\\Test","output.txt");
            buffer = new BufferedReader(new InputStreamReader(System.in));
            FileWriter writer = new FileWriter(f,true);
            out = new PrintWriter(writer);
            out.println(buffer.readLine());
            
      } catch (IOException e) {
            e.printStackTrace();
      }finally {
            try {
                  buffer.close();
                  out.close();
            } catch (IOException e) {
                  e.printStackTrace();
            }
      }
      }
}




import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class FileTest01 {

    public static void main(String[] args) {
        //writhe는 없으면 자동생성된ㄷ
        File f = new File("c:\\Test\\xyz.java");
        //데이터 쓰기: FileWriter, FileOutputStream.
        BufferedReader buffer =  null;
        try {
            FileReader reader = new FileReader(f);
            buffer = new BufferedReader(reader);
            String data = buffer.readLine();    
            while(data != null) {
                System.out.println(data);
                data = buffer.readLine();    
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch(IOException e) {
            e.printStackTrace();
        }finally {
            try {
                buffer.close();
            }catch(IOException e) {
                e.printStackTrace();
            }
        }

    }

}


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 java.io.PrintWriter;

public class FileW {

    public static void main(String[] args) {
        //writhe는 없으면 자동생성된다.
                File f = new File("c:\\Test\\xyz.java");
                //데이터 쓰기: FileWriter, FileOutputStream.
                PrintWriter out = null;
                try {
                    FileWriter writher = new FileWriter(f,true); //append
                    //필터
                    out = new PrintWriter(writher);
                    out.print("happy");                    
                } catch(IOException e) {
                    e.printStackTrace();
                }finally {
                        out.close();
                    
                }

    }

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class FileDel {

    public static void main(String[] args) {
    
        Path newFile= Paths.get("c:\\Test\\xxx.txt");
        Path xx2= Paths.get("c:\\Test\\xxx.txt");;
//        try {//파일생성
//            xx2= Files.createFile(newFile);            
//        }catch(IOException e) {
//            e.printStackTrace();
//        }
        
//        try {//파일 삭제
//            Files.deleteIfExists(xx2);
//        } catch (IOException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
        Path original = Paths.get("c:\\Test\\IOTest5.java");
        Path copy= Paths.get("c:\\Test\\IOTest5Copy.java");
        
        try {
            Path yyy= Files.copy(original, copy, StandardCopyOption.REPLACE_EXISTING);
            System.out.println(yyy);
        } catch (IOException e) {
            // TODO Auto-generated catch
            
            e.printStackTrace();
        }
    }

}

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class IOTest10_Serial_In {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ObjectInputStream ois = null;
        try {        
            File f = new File("C:\\Test","serial.dat");
            FileInputStream fis = new FileInputStream(f);
            ois = new ObjectInputStream(fis);
            Person p = (Person)ois.readObject();
            System.out.println(p.getName()+"\t"+p.getAge());            
        } catch (IOException e) {
            e.printStackTrace();
        }catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        finally {
        try {
            ois.close();
        }catch (IOException e) {
            e.printStackTrace();
        }
        }
    }

}

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class IOTest10_Serial_Out {

    public static void main(String[] args) {
        //생성된 객체의 멤버 변수 값 저장 단 class는 반드시
        //implements
        ObjectOutputStream oos = null;
        try {
            Person p = new Person("홍길동",20);
            File f = new File("C:\\Test","serial.dat");
            FileOutputStream fos = new FileOutputStream(f);
            oos = new ObjectOutputStream(fos);
            oos.writeObject(p);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
        try {
            oos.close();
        }catch (IOException e) {
            e.printStackTrace();
        }
        }

    }

}

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class IOTest_11_File {

    public static void main(String[] args) {
        Path path= Paths.get("c:\\Test");
        boolean exsits= Files.exists(path);
        System.out.println("foldre exisit==="+ exsits);
        boolean readable=Files.isReadable(path);
        boolean writable = Files.isWritable(path);
        boolean executable= Files.isExecutable(path);
        System.out.println(readable+ "\t"+ writable+ "\t"+ executable);
        
        //파일 및 디렉토리 생성
        Path newdir= Paths.get("c:\\Test\\ccc");//디렉토리생성
        try {
            Path xxx= Files.createDirectories(newdir);
            System.out.println("path ====="+ xxx);
        }catch(IOException e) {
            e.printStackTrace();
        }
        Path newFile= Paths.get("c:\\Test\\xxx.txt");
        Path xx2= null;
        try {
            xx2= Files.createFile(newFile);            
        }catch(IOException e) {
            e.printStackTrace();
        }
    
        //파일 디렉토리 삭제
        try {
            Files.delete(newdir);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        try {
            Files.deleteIfExists(xx2);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        
        //파일 또는 디렉토리 복사
        Path original = Paths.get("c:\\Test\\IOTest5.java");
        Path copy= Paths.get("c:\\Test\\IOTest5Copy.java");
        
        try {
            Path yyy= Files.copy(original, copy, StandardCopyOption.REPLACE_EXISTING);
            System.out.println(yyy);
        } catch (IOException e) {
            // TODO Auto-generated catch
            
            e.printStackTrace();
        }
        
    }

}

import java.nio.file.Path;
import java.nio.file.Paths;

public class IOTest11_Path {

    public static void main(String[] args) {
        Path path= Paths.get("c:\\Test\\IOTest5.java");
        System.out.println("getFileName==="+ path.getFileName());
        System.out.println("getParent==="+ path.getParent());
        System.out.println("isAbsoluet"+ path.isAbsolute());
    //uri반환
        URI uri = path.toUri();
        
        System.out.println("uri====="+ uri);
        //절대경로를 사용하는 path반환
        Path xxx= Paths.get("IOTest.java");
        Path xxx2= xxx.toAbsolutePath();
        System.out.println("AbsolutePath======"+xxx2);
        //supath:하위경로를 만들어 일부를 가져옴
        
        Path yyy= Paths.get("c:\\\\Test\\\\IOTest5.java");
        Path yyy2= yyy.subpath(0,1);
        System.out.println("subPath======"+yyy);
        
        //경로의 결합
        Path p1= Paths.get("c:\\Temp\\aaa");
        Path p2= Paths.get("test.txt");
        Path p3= p1.resolve(p2);
        System.out.println("resolve====="+ p3);
        

    }

}

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ScannerFile {

    public static void main(String[] args) {
    File f = new File("c:\\test","xyz.java");
    Scanner scan = null;
    try {
        scan = new Scanner(f);
        while(scan.hasNext()) {
            System.out.println(scan.nextLine());
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }finally {
        if(scan !=null)scan.close();
    }

    }

}



import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Test {
      public static void main(String[] args) {
            FileInputStream fis = null;
            FileOutputStream fos = null;
            try {
                  File readFile = new File("c:\\Test","a.jpg");
                  File writeFile = new File("c:\\Test","b.jpg");
                  int size = (int)readFile.length();
                  byte [] readByte = new byte[size];
                  fis = new FileInputStream(readFile);
                  fos = new FileOutputStream(writeFile);
                  int n = fis.read(readByte);
                  fos.write(readByte);          
            } catch (Exception e) {
            e.printStackTrace();
            }finally {
                  try {
                        fis.close();
                        fos.close();
                  }catch(IOException e) {
                        e.printStackTrace();
                  }
            }
      }
}

//읽을 곳 read, 쓸 곳은 file

new에서 생성되있는 객체의 데이터 가져오기가 가능하다.




댓글()
loading