프로그래밍/Java

Shape File을 CSV로 변환하기(2)-geotools lib을 이용하여 File 변환하여 쓰기

kingroad 2019. 11. 20. 13:13

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

import org.opengis.feature.Property;
import org.opengis.feature.simple.SimpleFeature;

public class App {

public static void main(String[] args) throws IOException {
String anotherInputFilePath = "C:\\Users\\king\\Desktop\\shapeFile\\a.shp";
String anotherOutputFilePath = "C:\\Users\\king\\Desktop\\shapeFile\\a.csv";

BufferedWriter bw = new BufferedWriter(new FileWriter(anotherOutputFilePath));

loadToShp loadShape = new loadToShp();
loadShape.DefaultLoad(anotherInputFilePath);
StringBuffer tmpStr = new StringBuffer();

List properties = (List) loadShape.getIter().next().getProperties();
// 프로퍼티 명
for (int i = 0; i < properties.size(); i++) {
if(i==(properties.size()-1)) {
tmpStr.append(properties.get(i).getName()).append("\n");
} else {
tmpStr.append(properties.get(i).getName()).append("|");
}
//tmpStr.append("\n");
//System.out.printf("%d번째 진행중",i);
}
bw.write(tmpStr.toString());
// 프로퍼티 명 쓰기 End

 

// 레코드를 파일에 쓰기
int x=0;

//파일이 너무 커서 레코드의 갯수를 저장하기용 또는 레코드가 잘 써지는지 10만줄에 따라 print해보기용

while(loadShape.getIter().hasNext()) {
if((x%100000)==0) {
System.out.println(tmpStr.toString());
}

//if(x==10){

//bw.close(); 
//break; }


tmpStr = new StringBuffer();
SimpleFeature f = loadShape.getIter().next();

for(int i=0; i<f.getAttributeCount(); i++) {
if(i==(f.getAttributeCount()-1)) {
tmpStr.append(f.getAttribute(i).toString()).append("\n");
} else {
tmpStr.append(f.getAttribute(i).toString()).append("|");
}
}
//System.out.println(tmpStr.toString());
bw.write(tmpStr.toString());
x++;

}
bw.close();
}
}

 

// csv file이 잘 써졋는지 확인을 하기 위해서 excel로 csv파일을 열었을 때 변환하려는 원본 파일이 너무 크다면

// 파일 용량은 증가했으나 백지로 열리는 경우가 있는데

// excel->데이터 항목->데이터 가져오기->파일에서->텍스트/csv->저장된 excel 파일 클릭->구분기호 지정 ex) | 또는 ,

// ->로드 순으로 열어서 확인해볼 수 있다

// 또한 데이터가 일치하지 않아 보일 수 있는데 excel의 문제이다. 파일 레코드를 소량만 변환하여 notepad++와 같은 // 다른 도구를 사용하여 확인을 해보면 정상적으로 변환됨을 확인할 수 있다.