[Java] URL로부터 데이터(문자열) 읽어오기

지정된 URL에 존재하는 데이터소스로부터 데이터, 특히 문자열 값으로 읽어오는 자바 코드입니다.

URL url = null;
try {
    url = new URL("http://222.237.78.208:8080/yp_tiles/a/metadata.xml");
} catch(MalformedURLException e1) {
    e1.printStackTrace();
}

InputStream in = null;
try {
    in = url.openStream();
    byte[] buffer = new byte[128];
    int readCount = 0;
    StringBuilder result = new StringBuilder();
   
    while((readCount = in.read(buffer)) != -1) {
        String part = new String(buffer, 0, readCount);
        result.append(part);
    }   
   
    System.out.println(result);
} 
catch (IOException e) {
    e.printStackTrace();
}

위의 코드를 실행하게 되면 해당 URL로부터 가져온 데이터가 문자열로써 result 변수에 저장됩니다. 저장된 결과에 대한 화면 표시는 다음과 같습니다.

사용자 삽입 이미지
위의 결과는 타일맵으로 가공된 데이터에 대한 메타 데이터입니다.

[Java] 파일 복사

fileName이 복사할 대상 파일이고 newFileName이 복사되어 새롭게 생성될 파일명입니다. 근데 좀 살펴볼게… 실제 데이터를 복사(전송) 시키는 12번 코드의 transfer 함수는 실제로 전송된 바이트 수를 반환합니다. 전송하고자 하는 바이트수와 실제로 전송된 바이트 수 사이에 차이가 있을 수 있다는 건데.. 이 부분에 대한 고민을 좀 더 해봐야할 코드입니다.

try {
    File inFile = new File(fileName);
    FileInputStream inputStream = new FileInputStream(inFile);
    
    File outFile = new File(newFileName);
    FileOutputStream outputStream = new FileOutputStream(outFile);
   
    FileChannel fcin = inputStream.getChannel();
    FileChannel fcout = outputStream.getChannel();
   
    long size = fcin.size();    
    fcin.transferTo(0, size, fcout);
   
    fcout.close();
    fcin.close();
    
    outputStream.close();
    inputStream.close();
} catch (Exception e) {
    e.printStackTrace();
}