기억 저장소

클라우드 기반 인공지능 개발과 DevOps 실무

카테고리 없음

Android java 파일 저장하기 / FileOutputStream / openFileOutput

하늘.98 2022. 8. 7. 21:56

 

Manifest

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
    android:requestLegacyExternalStorage="true"

Main Activity

package com.jhn.testfile;

import androidx.appcompat.app.AppCompatActivity;



import android.content.Context;
import android.os.Bundle;

import android.view.View;
import android.widget.Button;
import android.widget.Toast;


import com.google.android.material.tabs.TabLayout;

import java.io.FileInputStream;
import java.io.FileOutputStream;


public class MainActivity extends AppCompatActivity {
    Button mButton;
    Button mReadButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mButton = findViewById(R.id.save_btn);
        mReadButton = findViewById(R.id.read_btn);


        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                try {
                    FileOutputStream outFs = openFileOutput("file_txt", Context.MODE_PRIVATE);
                    String msg = "성공적인 데이터";
                    outFs.write(msg.getBytes());
                    Toast.makeText(getApplicationContext(),"성공적",Toast.LENGTH_SHORT).show();

                }catch (Exception e){
                    Toast.makeText(getApplicationContext(),"실패",Toast.LENGTH_SHORT).show();
                    e.getStackTrace();

                }
            }
        });

        mReadButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                try {
                    FileInputStream inFs = openFileInput("file_txt");
                    byte[] result = new byte[1024];
                    int resultLength = inFs.read(result);
                    String data = new String(result,"utf-8");
                    Toast.makeText(getApplicationContext(),data,Toast.LENGTH_SHORT).show();

                }catch (Exception e ){
                    Toast.makeText(getApplicationContext(),"실패",Toast.LENGTH_SHORT).show();
                    e.getStackTrace();
                }
            }
        });

    }

}

 

File 가져올때는 아래 코드를 대입해서 쓰는게 

byte를 필요한 만큼가져와서 더 사용하기 좋다 .

FileInputStream inFs = openFileInput("jsonData.txt");
int fileSize = inFs.available();
byte[] buffer = new byte[fileSize];
if(null == inFs)Log.d(TAG,"setFile inFs = null");
Log.d(TAG, "setFile inFs  = " + inFs);
inFs.read(buffer);
inFs.close();
data = new String(buffer, "utf-8");
Log.d(TAG, "setFile data  = " + data);

 

 

 

main Layout

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/save_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="저장!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/read_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="가져오기!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.591" />


</androidx.constraintlayout.widget.ConstraintLayout>

`

 

Device File Explorer - data 폴더 - data 폴더 - com.example.(이름) 폴더 - file 폴더 에서 확인하기

 

 

 

 

 

가져오기 버튼을 누르면 데이터를 가져온다 "성공적인 데이터" 이게 파일에 저장되어 있었다.