본문 바로가기
안드로이드(android)

Android(Kotlin) / 현재위치 txt 파일로 저장

by clean_h 2021. 1. 28.
728x90

내부 저장소 파일 입출력


www.youtube.com/watch?v=XDD1gqrjfr0

을 보고 내부 저장소 파일 입출력을 진행하였다. 

// 내부 저장소

override fun onCreate(savedInstanceState: Bundle?) {
	super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    
    //내부 저장소 경로를 가져옴
    val dir = fileDirs.absolutePath //내부경로의 절대 경로
    val filename = "파일이름.txt"
    val contentes = "파일 내용\n"
    
    writeTextFile(dir, filename, contents) //파일 쓰기
    
    val result = readTextFile(dir + "/" + filename)
    Log.d("파일 내용", result) // 파일 내용 출력
    
}


// 파일 쓰기
fun writeTextFile(directory:String, filename:String, content:String){
	
    val dir = File(directory)
    
    if(!dir.exists()){ //dir이 존재 하지 않을때 
    	dir.mkdirs() //mkdirs : 중간에 directory가 없어도 생성됨
    }
    
    val writer = FileWriter(directory + "/" + filename)
    //full path = directory + "/" +filename
    
    //쓰기 속도 향상
    val buffer = BufferedWriter(writer)
    buffer.write(content)
    buffer.close()
}

//파일 읽기
fun readTextFile(fullpath:String) : String{
	val file = File(fullpath)
    if(!file.exists()) return "" //파일이 존재하지 않을때
    
    val reader = FileReader(file)
    val buffer = BufferedReader(reader)
    
    var temp:String? = ""
    var result = StringBuffer()
    
    while(true){
    	temp = buffer.readLine() // 줄단위로 read
        if(temp == null) break
        else result.append(temp).append("\n")
    }
    buffer.close()
    return result.toString()
}

 

파일 입출력을 진행하였다. 

 

 

 

이를 바탕으로 현재위치 txt 파일로 저장해본다.

 

 

현재위치 txt 파일로 저장


2021/01/28 - [안드로이드(android)] - Android(Kotlin) / 네이비지도에 현재 위치 표시하기

지금까지 공부한 내용으로 1초마다 받아온 현재 위치를 txt 파일에 저장한다.

    fun setUpdateLocationListner() {
        
        val dir = filesDir.absolutePath //내부저장소 절대 경로
        val filename = "실제 GPS.txt"
        writeTextFile(dir, filename, "애플리케이션 시작!\n")

        val locationRequest = LocationRequest.create()
        locationRequest.run {
            priority = LocationRequest.PRIORITY_HIGH_ACCURACY //높은 정확도
            interval = 1000 //1초에 한번씩 GPS 요청
        }

        locationCallback = object : LocationCallback() {
            override fun onLocationResult(locationResult: LocationResult?) {
                locationResult ?: return
                for ((i, location) in locationResult.locations.withIndex()) {
                    Log.d("location: ", "${location.latitude}, ${location.longitude}")
                    setLastLocation(location)
                    val contents = "GPS = " + location.latitude.toString() + "\t" + location.longitude.toString() + "\n"
                    writeTextFile(dir, filename, contents)
                }
            }
        }
        //location 요청 함수 호출 (locationRequest, locationCallback)

        fusedLocationProviderClient.requestLocationUpdates(
            locationRequest,
            locationCallback,
            Looper.myLooper()
        )
    }//좌표계를 주기적으로 갱신

 

다음 함수는 1초에 한번씩 GPS를 요청하여 위도와 경도를 출력한다.

 

내부저장소의 절대 경로와 파일 이름을 지정해준다.

wirteTextFile 함수에 경로와 파일 이름, 저장할 contents를 입력하여 파일을 저장할 수 있다. 

 

writeTextFile 함수는 다음과 같다.

fun writeTextFile(directory:String, filename:String, content:String){
	val dir = File(directory)

	if(!dir.exists()){ //dir이 존재 하지 않을때
		dir.mkdirs() //mkdirs : 중간에 directory가 없어도 생성됨
	}

	val writer = FileWriter(directory + "/" + filename, true)
	//true는 파일을 이어쓰는 것을 의미

	//쓰기 속도 향상
	val buffer = BufferedWriter(writer)
	buffer.write(content)
	buffer.close()
}

현재 좌표를 저장할 수 있다.

 

FileWriter를 사용할때 true를 입력하면 파일을 이어서 쓰는 것이 가능하다.

 

내부 저장소의 위치는 data->data->com.example.'프로젝트명'->files에 위치해 있다. 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

실행을 시켜 보면 다음과 같은 위치에 실제 GPS.txt가 저장되어있는 것을 확인할 수 있다. 

 

 

실제 GPS.txt

애플리케이션을 실행한 후 부터 종료될 때까지 1초마다 GPS값을 저장해 준 결과를 확인할 수 있다.

실제 애플리케이션을 테스트 해본 것이 아니기 때문에 좌표가 똑같이 나왔다.

728x90

댓글