반응형
//ResTemplate 생성
RestTemplate restTemplate = new RestTemplate();

//헤더 생성
HttpHeaders headers = new HttpHeaders();     
headers.add("Accept", MediaType.APPLICATION_JSON_VALUE);
headers.add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8");

//url을 생성해줍니다...
URI url = URI.create("http://testapi.co.kr/v1");
       
//url을 호출하고 응답을 받는다...
RequestEntity<String> req = new RequestEntity<>(headers, HttpMethod.GET, url);
ResponseEntity<String> res = restTemplate.exchange(req, String.class);

//JSON Object로 body를 얻어본다...
JSONObject jObj = new JSONObject(res.getBody());

//JSON object의 key를 뽑아본다...
Iterator keys = jObj.keys();

//JSON object의 key를 String 리스트에 담아버릴것이다..
List<String> stringKey = new ArrayList<>();

//이제 이 key는 제겁니다.
while(keys.hasNext()) {
	String key = keys.next().toString();
	stringKey.add(key);
}


//key로 value 갖고오기.
for(int k=0; k< stringKey.size();k++){
	JSONObject ob = (JSONObject) jObj.get(stringKey.get(k));
	JSONObject dataObj = (JSONObject) ob.get("data");

}
//예시1) API 결과 데이터가 다음과 같은 경우
//[{"a1":"01","a2":"02"},{"b1":11,"b2":12}]

JSONArray ja = new JSONArray(res.getBody());
JSONObject tmpjbj = ja.getJSONObject(0); //결과 : {"a1":"01","a2":"02"}



//예시2) API 결과 데이터가 다음과 같은 경우
//{"no1":{"result":200,"data":{"apple":1,"banana":2}},"no2":{"result":500,"data":{"punch":"teeth","corn":"3"}}}

JSONObject jb = new JSONObject(res.getBody());
JSONObject no1ob = jb.getJSONObject("no1"); //결과 : {"result":200,"data":{"apple":1,"banana":2}}
반응형
반응형

파일 및 디렉터리 삭제 방법

디렉터리 안의 파일을 모두 제거해야 디렉터리가 삭제되므로 파일먼저 삭제.

String datePath = "\\src\\main\\resources\\static\\assets\\data\\data1";
File dateFolder = new File(datePath);

File dir[] = dateFolder.listFiles();

 try {
		for (int i = 0; i < dir.length; i++) {
			dir[i].delete(); //파일 삭제
		}

		dateFolder.delete(); //폴더 삭제


	}catch (Exception e){
		e.printStackTrace();
	}

Exception 에러도 없이 삭제가 안 되는 파일이 있었다.

이유 : 해당 파일을 어딘가에서 붙잡고 있음.

delete 이전에 파일을 읽어오는 소스가 있는데 IO stream을 안 닫아 줬기 때문.

///수정 전 
/////Scanner를 닫아야 하는데 안 닫았음. 

try{
	Scanner commentScan = new Scanner(new File(dir[i] + "\\comment"));
	mtDto.setComment(commentScan.nextLine());
}catch(Exception e){

}

try catch를 사용하는 경우 try에서도 닫고 catch에서도 닫아줘야함...

 

결론 : try-with-resource를 사용하면 예외가 발생했든 안 했든간에 사용했던 리소스 객체를 자동으로 닫아주므로

try with resource를 사용하자.

///수정 후

try ( Scanner commentScan = new Scanner(new File(dir[i] + "\\comment")); )
{
	mtDto.setComment(commentScan.nextLine());
}catch(Exception e){

}
반응형
반응형

1. System.getProperty("user.dir")

현재 작업 path

String cwd = System.getProperty("user.dir");

System.out.println("현재 경로 : "+cwd);
//현재 실행 프로젝트 경로가 출력됨
//현재 경로 : D:\myProject

 

2. listFiles()

특정 파일/디렉터리 아래의 파일들 full path

File dirs = new File(cwd + "\\src\\main\\resources\\static\\assets\\data");

File dir[] = dirs.listFiles();

for(int i=0;i<dir.length;i++){
    System.out.println("지정한 경로 아래의 파일 경로 : " + dir[i]);
}

//디렉터리 아래에 있는 파일or디렉터리들의 full path가 출력됨.
//지정한 경로 아래의 파일 경로 : D:\myProject\src\main\resources\static\assets\data\file1
//지정한 경로 아래의 파일 경로 : D:\myProject\src\main\resources\static\assets\data\fil2
//지정한 경로 아래의 파일 경로 : D:\myProject\src\main\resources\static\assets\data\folder1

 

3. list()

특정 파일/디렉터리 아래의 파일들 이름 출력

File dirs = new File(cwd + "\\src\\main\\resources\\static\\assets\\data");

String dirName[] = dirs.list();

for(int i=0;i<dirName.length;i++){
    System.out.println("지정한 경로 아래의 파일 : " + dirName[i]);
}

//디렉터리 아래에 있는 파일or디렉터리들의 이름만 출려됨
//지정한 경로 아래의 파일 : file1
//지정한 경로 아래의 파일 : file2
//지정한 경로 아래의 파일 : folder1
반응형
반응형

머 이런 값을 가진 Map 이 있다고하자

{a=1,b=2,c=null}

 

c라는 key로 접근 -> value가 null

d라는 key로 접근 -> key가 없어서 NullPointerException

map.get("c")  //null값 
map.get("d") //NullPointerException

 

get 대신에 getOrDefault를 사용하면 된다. key 뒤에는 null일 경우 사용할 디폴트값을 지정해준다.

map.getOrDefault("c","-999");
map.getOrDefault("d","-999");​
반응형
반응형

BigDecimal 객체를 이용한다. 

BigDecimal test1 = new BigDecimal(2021061523295E11);
System.out.println(test1); ////202106152329500000518144

///// String -> double 파싱 후 BigDecimal 객체 생성
BigDecimal test2 = new BigDecimal(Double.parseDouble("2021061523295E11"));
System.out.println(test2); ////202106152329500000518144


///// BigDecimal 객체 -> String 객체
String str = test2.toString();

 

반응형
반응형

build.gradle에서 의존성 추가

implementation 'org.apache.commons:commons-lang3:3.0'

 

길이가 3인 두개의 배열이 있다

String[] strs1 = {"a","b","c"};
String[] strs2 = {"d","e","f"};



여기에 배열 길이를 초과해서 인덱스3에 "g"라는 요소를 대입하면

될리가 없다. Exception 나버림.

strs2[3] = "g";

-> java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3


 

해결방법 : ArrayUtils를 사용해서 붙여준다.

ArrayUtils.add(기존배열,붙일요소);

String[] strs3 = ArrayUtils.add(strs2,"g");


/////잘 붙었는지 출력해보자
for(int i=0; i< strs3.length;i++){
     System.out.println(strs3[i]);
}

d
e
f
g
/////잘 붙었다





배열 + 배열도 가능하다

ArrayUtils.addAll(기존배열,붙일배열);

strs3 = ArrayUtils.addAll(strs1,strs3);


/////잘 붙었는지 출력해보자
for(int i=0; i< strs3.length;i++){
	System.out.println(strs3[i]);
}

a
b
c
d
e
f
g
/////잘 붙었다
반응형
반응형

Date 객체로 오늘 날짜 가져오기

1) Date 객체 생성, date객체를 직접 찍어봄

2) getTime()메소드 사용(1970년 1/1 부터 주어진 날짜 사이의 경과시간이 반환됨)

///// 1) Date 객체 생성해서 찍어보기
Date myDate = new Date();
System.out.println(myDate); //Fri Sep 03 11:34:26 KST 2021

///// 2) getTime() 
//1970 년 1 월 1 일 00:00:00 UTC와 주어진 날짜 사이의 경과 시간 (밀리 초)을 나타냄
System.out.println(myDate.getTime()); //1630635552571

 


Date 객체에 원하는 날짜 설정하기

1) setTime() 메소드 사용 (1970년 1/1과 세팅하려는 날짜 사이의 경과시간으로 세팅해야됨)

2) SimpleDateFormat을 이용한 세팅

Date myDate = new Date();

///// 1) setTime()
//1970 년 1 월 1 일 00:00:00 UTC와 설정하려는 날짜 사이의 밀리초로 세팅해야됨
myDate.setTime(1609426800000L);
System.out.println(myDate.getTime()); //1609426800000


///// 2) simpleDateFormat으로 String타입 날짜를 date로 변환하여 넣는다.
String myString = "20210101";
SimpleDateFormat dtFormat = new SimpleDateFormat("yyyyMMdd");
Date mydate = dtFormat.parse(myString);

System.out.println(mydate); //Fri Jan 01 00:00:00 KST 2021

 


Calendar 객체로 오늘 날짜 가져오기

1) setTime 으로 오늘날짜 지정 -> getTime으로 날짜 가져오기

2) cal.get(Calendar.YEAR)

* MONTH 는 0부터 시작이므로 0이 1월임. 즉 9월은 8이 출력됨.

//Calendar 객체 생성
Calendar cal = Calendar.getInstance();

///// 오늘 날짜 설정
cal.setTime(new Date());
System.out.println(cal.getTime()); //Fri Sep 03 11:23:48 KST 2021


System.out.println(cal.get(Calendar.YEAR)); /// 년도 2021
System.out.println(cal.get(Calendar.MONTH)); /// 달 8
System.out.println(cal.get(Calendar.DATE)); /// 날짜 3
System.out.println(cal.get(Calendar.HOUR));  /// 시간 
System.out.println(cal.get(Calendar.MINUTE)); /// 분 
System.out.println(cal.get(Calendar.SECOND)); /// 초

Calendar 객체에 원하는 날짜 설정하기

1) set 메소드 사용. 년, 월, 일 값으로 설정

2) setTime 메소드 사용. Date 객체로 설정

Calendar cal = Calendar.getInstance();

///// 1) set 메소드(년,월,일)
cal.set(2021,8,1);
System.out.println(cal.getTime()); //Wed Sep 01 11:23:48 KST 2021


///// 2) setTime 메소드(Date객체)
cal.setTime(mydate);
System.out.println(cal.getTime()); //Fri Jan 01 00:00:00 KST 2021

 


날짜 계산하기

1) 1일 뒤 날짜 구하기 : cal.add(Calendar.Date, 1)

2) 1달 뒤 날짜 구하기 : cal.cadd(Calendar.Month, 1);

3) 두 날짜 사이이의 간격 구하기

Calendar cal = Calendar.getInstance();
cal.setTime(new Date());

///// 오늘날짜 +1 => 내일
cal.add(Calendar.DATE,1);
System.out.println(cal.getTime()); //Thu Sep 02 11:23:48 KST 2021

///// 오늘날짜 -7 => 7일 전(일주일 전)
cal.add(Calendar.DATE,-7);

///// 오늘 달 +1 => 다음 달
cal.add(Calendar.MONTH,1);
System.out.println(cal.getTime()); //Sat Oct 02 11:23:48 KST 2021

///// 오늘 달 -1 => 저번 달
cal.add(Calendar.Month,-1);


///// 두 날짜 사이의 간격 구하기 (일 수)
SimpleDateFormat dtFormat = new SimpleDateFormat("yyyy/MM/dd");
Date sTime = dtFormat.parse("20210801");
Date eTime = dtFormat.parse("20210901");
long diffDays = (eTime.getTime() - sTime.getTime()) / 1000 / (24*60*60);

 


String -> Date

String myString = "20210101";
SimpleDateFormat dtFormat = new SimpleDateFormat("yyyyMMdd");
Date myDate = dtFormat.parse(myString);

System.out.println(myDate);
//Fri Sep 03 00:00:00 KST 2021

 

Date -> String

Date myDate = new Date();
SimpleDateFormat dtFormat = new SimpleDateFormat("yyyyMMdd");
String myString = dtFormat.format(myDate);

 

Calendar -> String

Calendar cal = Calendar.getInstance();
cal.set(2021,0,1);

SimpleDateFormat dtFormat = new SimpleDateFormat("yyyyMMdd");
String myString = dtFormat.format(cal.getTime());

System.out.println(myString); //20210101

 

String -> Calendar

String myString = "20210101";
SimpleDateFormat dtFormat = new SimpleDateFormat("yyyyMMdd");
Date myDate = dtFormat.parse(myString);
cal.setTime(mydate);

System.out.println(cal.getTime());

 

Timestamp -> String

Date st = new Date(Integer.parseInt(timestamp)*1000L);
SimpleDateFormat dtFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String result = dtFormat.format(st);
반응형
반응형

의존성 추가

compile "org.apache.commons:commons-csv:1.8"

 

java 메소드

@GetMapping(value = "/returnCSV", produces = "text/csv")
public ResponseEntity<Resource> exportCSV() {

	///////csv 컬럼명
	String[] csvHeader = { "번호", "이름", "나이" };

	//////csv 데이터
	List<List<String>> csvBody = new ArrayList<>();
	csvBody.add(Arrays.asList("1", "Williams", "25"));
	csvBody.add(Arrays.asList("2", "Smith", "44"));
	csvBody.add(Arrays.asList("3", "Brown", "31"));

	ByteArrayInputStream byteArrayOutputStream;

	try (
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		CSVPrinter csvPrinter = new CSVPrinter(new PrintWriter(out),CSVFormat.DEFAULT.withHeader(csvHeader));
	){
		for (List<String> record : csvBody){
			csvPrinter.printRecord(record); 
		}
		csvPrinter.flush();
		byteArrayOutputStream = new ByteArrayInputStream(out.toByteArray());
    	
	} catch (IOException e) {
		throw new RuntimeException(e.getMessage());
	}

	InputStreamResource fileInputStream = new InputStreamResource(byteArrayOutputStream);

	String csvFileName = "people.csv";

	//////Http 헤더설정
	HttpHeaders headers = new HttpHeaders();
	headers.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + csvFileName);
		
	//////Content Type 설정(text/csv)
	headers.set(HttpHeaders.CONTENT_TYPE, "text/csv");

	return new ResponseEntity<Resource>(fileInputStream,headers,HttpStatus.OK);
}

 

전달되는 데이터는 이렇게 생김

번호,이름,나이
1,Williams,25
2,Smith,44
3,Brown,31

 

웹에서 csv 전달받는 javascript 코드

전달받은 csv 을 웹에서 파일로 다운로드 

fetch("http://localhost:8080/test",{
                    method : 'POST',
                    mode : 'cors',
                    cache : 'no-cache',
                    headers: {'Content-Type': 'application/json'},
                    credentials : 'same-origin',
                    redirect : 'follow',
                    referrer : 'no-referrer',
                    body: JSON.stringify(obj),
}).then(response => response.text())
  .then(function(res){
  	let csv=[];
	csv.push(res);
    
	////////한글 처리를 해주기 위해 BOM 추가
	csv = "\uFEFF" + csv;

	let csvFile = new Blob([csv], { type: "text/csv" });
	let downloadLink = document.createElement("a");
	downloadLink.download = "filename.csv";
	downloadLink.href = window.URL.createObjectURL(csvFile);
	downloadLink.style.display = "none";
	document.body.appendChild(downloadLink);
 	downloadLink.click();
})

 

 


Javascript에서 csv 생성 및 다운로드

 

[JavaScript] CSV 생성 및 다운로드

1. 다운로드 버튼 클릭 이벤트 $("#excelDownload").click(function () { let filename = "testFile.csv"; getCSV(filename); }); 2. CSV 생성 함수 function getCSV(filename) { var csv = []; var row = []; //1..

mchch.tistory.com

 

fetch 사용

 

[JavaScript] fetch 사용법, fetch 응답 사용, fetch 변수 사용

ajax 대신 사용하는 api 호출 방법 fetch() 기본 //fetch를 호출하면 브라우저는 네트워크 요청을 보내고 promise를 반환한다. let promise = fetch(url, {options}) fetch(url, options) //api호출 성공 시 응답(..

mchch.tistory.com

 

csv return 방법 참고

 

Returning CSV Content From an API in Spring Boot

Avoiding conversion overhead by returning CSV data directly

codeburst.io

 

반응형
반응형

의존성 추가

dependencies {

    implementation 'org.apache.poi:poi:3.15'
    implementation 'org.apache.poi:poi-ooxml:3.15'
    implementation 'commons-io:commons-io:2.4'

}

 

열이 세 개인 파일을 읽으려 한다.

 

excel 읽는 메소드

public JSONArray readExcel(MultipartFile excelFile) {
        JSONArray jsonArray = new JSONArray();
        
        try{
            XSSFWorkbook workbook = new XSSFWorkbook(excelFile.getInputStream());
            XSSFSheet sheet;
            XSSFRow curRow;
            XSSFCell curCell;
            
            /////////첫번째 시트 읽기
            sheet = workbook.getSheetAt(0);
            
            /////////행의 개수 
            int rownum = sheet.getLastRowNum();
            
            /////////첫 행은 컬럼명이므로 두번째 행인 index1부터 읽기
            for(int rowIndex=1;rowIndex<=rownum;rowIndex++){
            
                /////////현재 index의 행 읽기
                curRow = sheet.getRow(rowIndex);
                
                /////////현재 행의 cell 개수
                int cellnum = curRow.getLastCellNum();
                
                /////////엑셀 데이터를 넣을 json object
                JSONObject data = new JSONObject();
                
                for(int cellIndex =0; cellIndex<cellnum;cellIndex++){
                    System.out.println(rowIndex+"행 "+cellIndex+"열의 값 : " + curRow.getCell(cellIndex));
                    switch(cellIndex){
                        case 0 : {    /////////첫번째 열 값
                            data.put("번호",curRow.getCell(cellIndex).getStringCellValue());
                        };break;
                        case 1 : {    /////////두번째 열 값
                            data.put("이름",curRow.getCell(cellIndex).getStringCellValue());
                        };break;
                        case 2 : {    /////////세번째 열 값
                            data.put("주소",curRow.getCell(cellIndex).getStringCellValue());
                        }break;
                    }
                }

                jsonArray.add(data);
            }
            return jsonArray;
        }catch(Exception e){
            System.out.println("ERROR : "  + e);
            return jsonArray;
        }
    }

 

반응형
반응형

 

//파일 쓰기
BufferedWriter bw = new BufferedWriter(new FileWriter("C:\Users\Owner\Desktop\newtext.txt",true));
bw.write("파일 쓰기");
bw.flush();


//파일 읽기
BufferedReader br = new BufferedReader(new FileReader("C:\Users\Owner\Desktop\oldtext.txt");
String line ="";
//한 줄 씩 읽은 내용 쓰기 
while( (line=br.readLine()) !=null ) {
	bw.newLine();
	bw.write(line);
	bw.flush();
}
반응형

+ Recent posts