본문 바로가기
IT 개발/Visual Studio C#

C# - 디렉토리 감시(FileSystemWatcher) 및 Upload(WebClient)하여 / JAVA - DB 삽입(POI - 엑셀 파일 DB 삽입)

by Love of fate 2020. 11. 30.
728x90
반응형

C#

[Program.cs]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
using System;
using System.IO;
 
namespace sensorModel
{
    class Program
    {
        static void Main(string[] args)
        {
            String dirPath = @"C:\Users\82109\Desktop\eunju\sp"; //감시할 디렉토리
 
            if (!Directory.Exists(dirPath)) //디렉토리가 있는지 없는지 확인
            {
                Directory.CreateDirectory(dirPath);
            }
 
            Console.WriteLine("종료하려면 ESC를 입력하세요.");
 
            DirectoryWatcher watcher = new DirectoryWatcher(); //DirectoryWatcher 객체 생성
            watcher.InitWatcher(dirPath);
 
            ConsoleKeyInfo consoleKeyInfo;
 
            while (true)
            {
               consoleKeyInfo = Console.ReadKey(); 
 
                if (consoleKeyInfo.Key == ConsoleKey.Escape) //키보드 ESC 누를 시 프로그램종료
                {
                    Environment.Exit(0);
                }
            }
        }
    }
}

 

[DirectoryWatcher.cs]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.IO;
using System.Net;
using System.Threading;
 
namespace sensorModel
{
    class DirectoryWatcher
    {
        FileSystemWatcher fileSystemWatcher;
        DateTime lastRead = DateTime.MinValue;
        WebClient client = new WebClient();
        Uri uploadUri = new Uri("http://455.215.4.252:8080/api/sec/upload.do");
 
        public void InitWatcher(string directoryPath)
        {
            fileSystemWatcher = new FileSystemWatcher();
 
            fileSystemWatcher.Path = directoryPath;
 
            //감시 파일 및 폴더의 filter 적용 : 필자는 마지막 수정날짜와, 생성 날짜 감시
            fileSystemWatcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.CreationTime; 
 
            //감시할 파일 유형 선택 예) *.* 모든 파일 
            fileSystemWatcher.Filter = "*.xlsx";
 
            // 하위폴더까지 포함시킬것인지 설정
            fileSystemWatcher.IncludeSubdirectories = true;
 
            //fileSystemWatcher.Created += new FileSystemEventHandler(FileSystemWatcher_Created);
            fileSystemWatcher.Changed += new FileSystemEventHandler(FileSystemWatcher_Changed);
 
            // 구성요소 활성화
            fileSystemWatcher.EnableRaisingEvents = true;
        }
 
        private void FileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
        {
            DateTime lastWriteTime = File.GetLastWriteTime(e.FullPath);
 
            //파일이 열렸을떄에도 이벤트가 먹음. 열렸을떄는 필요없기 ~가 없을 때 실행
            if (!e.Name.StartsWith("~")) 
            {
                // 나노초로 계산하여 1000000보다 클 경우 다음소스 진행
                if (lastWriteTime.Ticks - lastRead.Ticks > 1000000
                {
                    Console.WriteLine("Change noticed: Object Name = {0}, Object Event: {1} File Content",
                     e.Name, e.ChangeType);
                    
                    Thread.Sleep(500);
 
                    //File을 다른데로 카피를 하여 파일 열고닫고의 해결 없이 파일을 넘길 수 있다.
                    File.Copy(e.FullPath, @"C:\sp\abc.xlsx"true); 
                    client.UploadFile(uploadUri, @"C:\sp\abc.xlsx");
;
                    lastRead = lastWriteTime;
                }
            }
        }
    }
}
 

JAVA

 

[SensorContoller.java]

1
2
3
4
5
6
7
8
9
10
11
12
13
@Autowired
public SensorService sensorService;
 
@RequestMapping(value = "/upload.do", method = {RequestMethod.POST})
public void uploadData(
   MultipartFile file //파일 넘어올때 MultipartFile을 쓴다.
) {
    try {
        sensorService.setSensorFileInputData(file);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

 

[SensorService.Interface]

1
2
3
4
5
6
7
8
9
10
11
12
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import org.springframework.web.multipart.MultipartFile;
 
public interface SensorService {
    
    public void setSensorFileInputData(MultipartFile file) throws Exception;
}
 
 

 

[SensorServiceImpl.java]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package com.enjoybt.mdriv.smartRiver.service.impl;
 
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
 
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
 
import com.enjoybt.framework.database.CommonDAO;
import com.enjoybt.mdriv.smartRiver.SensorDTO;
import com.enjoybt.mdriv.smartRiver.service.SensorService;
 
@Service
public class SensorServiceImpl implements SensorService {
 
    @Autowired
    private CommonDAO mainDAO;
 
    @Override
    public void setSensorFileInputData(MultipartFile file) throws Exception {
 
        InputStream inputStream = new ByteArrayInputStream(file.getBytes());
        List<SensorDTO> list = new ArrayList<SensorDTO>();
 
        String extension = FilenameUtils.getExtension(file.getOriginalFilename()); // 3
 
        // 엑셀 로드 XSSFWorkbookFactory
        Workbook workbook = null;
        if (extension.equals("xlsx")) {
            workbook = new XSSFWorkbook(file.getInputStream());
        } else if (extension.equals("xls")) {
            workbook = new HSSFWorkbook(file.getInputStream());
        }
 
        // 시트 로드 0, 첫번째 시트 로드
        XSSFSheet sheet = (XSSFSheet) workbook.getSheetAt(0);
        XSSFRow row;
        XSSFCell cell;
 
        int rows = sheet.getLastRowNum(); // 행
 
        for (int i = 1; i <= rows; i++) { // 1부터 시작 첫번째 행 건너 뚜기
 
            row = sheet.getRow(i); // Row 읽기
 
            int cells = row.getLastCellNum(); // 셀
            SensorDTO sensorDto = new SensorDTO();
 
            String tgt_dttm = null;
            for (int cellIndex = 0; cellIndex < cells; cellIndex++) {
                cell = row.getCell(cellIndex);
 
                switch (cell.getColumnIndex()) {
                case 0// 관측일시
                    tgt_dttm = cell.getStringCellValue();
                    break;
                case 1// 개도
                    // 셀이 숫자일 경우
                    sensorDto.setCnvrRate((float) cell.getNumericCellValue()); 
                    break;
                case 2// 높이
                    sensorDto.setHght((float) cell.getNumericCellValue());
                    break;
                case 3// 수위
                    sensorDto.setWl((float) cell.getNumericCellValue());
                    break;
                case 4// 운영타입
                    sensorDto.setOper_type((String) cell.getStringCellValue());
                    break;
                }
                
                if (tgt_dttm.equals(null|| tgt_dttm == null) {
                    break;
                }else {
                    sensorDto.setTgt_dttm(tgt_dttm);
                }
            }
            list.add(sensorDto);
        }
 
        mainDAO.insert("sensor.insertSensorInputData", list);
    }
}

 

[실행결과]

파일 새로 생성했을때
DB 삽입

728x90
반응형

'IT 개발 > Visual Studio C#' 카테고리의 다른 글

C# 콘솔 프로그램 제작  (0) 2020.11.30