programing

Android에서 파일 읽기/쓰기 문자열

prostudy 2022. 5. 19. 22:35
반응형

Android에서 파일 읽기/쓰기 문자열

EditText에서 텍스트를 입력하여 내부 저장소에 파일을 저장하고자 한다.그런 다음 입력된 텍스트를 문자열 양식에 반환하고 나중에 사용할 다른 문자열에 저장하십시오.

암호는 다음과 같다.

package com.omm.easybalancerecharge;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

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

        final EditText num = (EditText) findViewById(R.id.sNum);
        Button ch = (Button) findViewById(R.id.rButton);
        TelephonyManager operator = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        String opname = operator.getNetworkOperatorName();
        TextView status = (TextView) findViewById(R.id.setStatus);
        final EditText ID = (EditText) findViewById(R.id.IQID);
        Button save = (Button) findViewById(R.id.sButton);

        final String myID = ""; //When Reading The File Back, I Need To Store It In This String For Later Use

        save.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                //Get Text From EditText "ID" And Save It To Internal Memory
            }
        });
        if (opname.contentEquals("zain SA")) {
            status.setText("Your Network Is: " + opname);
        } else {
            status.setText("No Network");
        }
        ch.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                //Read From The Saved File Here And Append It To String "myID"


                String hash = Uri.encode("#");
                Intent intent = new Intent(Intent.ACTION_CALL);
                intent.setData(Uri.parse("tel:*141*" + /*Use The String With Data Retrieved Here*/ num.getText()
                        + hash));
                startActivity(intent);
            }
        });
    }

작업/변수 사용 위치에 대한 내 요점을 더 분석하는 데 도움이 되는 코멘트를 포함했다.

이것이 너에게 유용하게 쓰이길 바란다.

파일 쓰기:

private void writeToFile(String data,Context context) {
    try {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE));
        outputStreamWriter.write(data);
        outputStreamWriter.close();
    }
    catch (IOException e) {
        Log.e("Exception", "File write failed: " + e.toString());
    } 
}

파일 읽기:

private String readFromFile(Context context) {

    String ret = "";

    try {
        InputStream inputStream = context.openFileInput("config.txt");

        if ( inputStream != null ) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String receiveString = "";
            StringBuilder stringBuilder = new StringBuilder();

            while ( (receiveString = bufferedReader.readLine()) != null ) {
                stringBuilder.append("\n").append(receiveString);
            }

            inputStream.close();
            ret = stringBuilder.toString();
        }
    }
    catch (FileNotFoundException e) {
        Log.e("login activity", "File not found: " + e.toString());
    } catch (IOException e) {
        Log.e("login activity", "Can not read file: " + e.toString());
    }

    return ret;
}

파일을 읽을 문자열을 읽고 쓰는 일반적인 전략을 찾고 있는 사용자:

먼저 파일 개체를 가져오십시오.

스토리지 경로가 필요할 겁니다.내부 스토리지의 경우 다음을 사용하십시오.

File path = context.getFilesDir();

외부 저장(SD 카드)의 경우 다음을 사용하십시오.

File path = context.getExternalFilesDir(null);

그런 다음 파일 개체를 만드십시오.

File file = new File(path, "my-file-name.txt");

파일에 문자열 쓰기

FileOutputStream stream = new FileOutputStream(file);
try {
    stream.write("text-to-write".getBytes());
} finally {
    stream.close();
}

또는 Google 과바와 함께

문자열 내용 = Files.toString(파일, StandardCharsets)UTF_8);

문자열로 파일 읽기

int length = (int) file.length();

byte[] bytes = new byte[length];

FileInputStream in = new FileInputStream(file);
try {
    in.read(bytes);
} finally {
    in.close();
}

String contents = new String(bytes);   

또는 Google Guava를 사용하는 경우

String contents = Files.toString(file,"UTF-8");

완전성을 위해 나는 언급할 것이다.

String contents = new Scanner(file).useDelimiter("\\A").next();

라이브러리는 필요 없지만 다른 옵션보다 50%~400% 느리게 벤치마킹할 수 있다(내 넥서스 5의 다양한 테스트에서).

메모들

각 전략에 대해 IOException을 파악하라는 요청을 받게 될 것이다.

Android의 기본 문자 인코딩은 UTF-8이다.

외부 스토리지를 사용하는 경우 매니페스트에 다음 중 하나를 추가하십시오.

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

또는

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

쓰기 권한은 읽기 권한을 의미하므로 둘 다 필요하지 않다.

public static void writeStringAsFile(final String fileContents, String fileName) {
    Context context = App.instance.getApplicationContext();
    try {
        FileWriter out = new FileWriter(new File(context.getFilesDir(), fileName));
        out.write(fileContents);
        out.close();
    } catch (IOException e) {
        Logger.logError(TAG, e);
    }
}

public static String readFileAsString(String fileName) {
    Context context = App.instance.getApplicationContext();
    StringBuilder stringBuilder = new StringBuilder();
    String line;
    BufferedReader in = null;

    try {
        in = new BufferedReader(new FileReader(new File(context.getFilesDir(), fileName)));
        while ((line = in.readLine()) != null) stringBuilder.append(line);

    } catch (FileNotFoundException e) {
        Logger.logError(TAG, e);
    } catch (IOException e) {
        Logger.logError(TAG, e);
    } 

    return stringBuilder.toString();
}

파일 메소드에서 문자열을 약간 수정하여 성능 향상

private String readFromFile(Context context, String fileName) {
    if (context == null) {
        return null;
    }

    String ret = "";

    try {
        InputStream inputStream = context.openFileInput(fileName);

        if ( inputStream != null ) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);               

            int size = inputStream.available();
            char[] buffer = new char[size];

            inputStreamReader.read(buffer);

            inputStream.close();
            ret = new String(buffer);
        }
    }catch (Exception e) {
        e.printStackTrace();
    }

    return ret;
}

아래 코드를 확인하다

파일 시스템의 파일에서 읽기.

FileInputStream fis = null;
    try {

        fis = context.openFileInput(fileName);
        InputStreamReader isr = new InputStreamReader(fis);
        // READ STRING OF UNKNOWN LENGTH
        StringBuilder sb = new StringBuilder();
        char[] inputBuffer = new char[2048];
        int l;
        // FILL BUFFER WITH DATA
        while ((l = isr.read(inputBuffer)) != -1) {
            sb.append(inputBuffer, 0, l);
        }
        // CONVERT BYTES TO STRING
        String readString = sb.toString();
        fis.close();

    catch (Exception e) {

    } finally {
        if (fis != null) {
            fis = null;
        }
    }

아래 코드는 내부 파일 시스템에 파일을 쓰는 것이다.

FileOutputStream fos = null;
    try {

        fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
        fos.write(stringdatatobestoredinfile.getBytes());
        fos.flush();
        fos.close();

    } catch (Exception e) {

    } finally {
        if (fos != null) {
            fos = null;
        }
    }

이게 너에게 도움이 될 것 같아.

난 좀 초보라서 오늘 이걸 작동시키느라 고생했어.

아래는 내가 끝마친 수업이다.그것은 효과가 있지만 나는 내 해결책이 얼마나 불완전한지 궁금했다.어쨌든, 좀 더 경험이 많은 사람들이 기꺼이 내 IO 클래스를 보고 조언을 해주길 바랐어.건배!

public class HighScore {
    File data = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator);
    File file = new File(data, "highscore.txt");
    private int highScore = 0;

    public int readHighScore() {
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            try {
                highScore = Integer.parseInt(br.readLine());
                br.close();
            } catch (NumberFormatException | IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            try {
                file.createNewFile();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
            e.printStackTrace();
        }
        return highScore;
    }

    public void writeHighScore(int highestScore) {
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter(file));
            bw.write(String.valueOf(highestScore));
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Kotlinbuiltin Extension 함수를 사용한 방법File

쓰기: yourFile.writeText(textFromEditText)
읽기: yourFile.readText()

가장 먼저 필요한 것은 AndroidManifest.xml의 권한이다.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

비동기식 태스크 코틀린 클래스에서는 파일 생성을 처리한다.

    import android.os.AsyncTask
    import android.os.Environment
    import android.util.Log
    import java.io.*
    class WriteFile: AsyncTask<String, Int, String>() {
        private val mFolder = "/MainFolder"
        lateinit var folder: File
        internal var writeThis = "string to cacheApp.txt"
        internal var cacheApptxt = "cacheApp.txt"
        override fun doInBackground(vararg writethis: String): String? {
            val received = writethis[0]
            if(received.isNotEmpty()){
                writeThis = received
            }
            folder = File(Environment.getExternalStorageDirectory(),"$mFolder/")
            if(!folder.exists()){
                folder.mkdir()
                val readME = File(folder, cacheApptxt)
                val file = File(readME.path)
                val out: BufferedWriter
                try {
                    out = BufferedWriter(FileWriter(file, true), 1024)
                    out.write(writeThis)
                    out.newLine()
                    out.close()
                    Log.d("Output_Success", folder.path)
                } catch (e: Exception) {
                    Log.d("Output_Exception", "$e")
                }
            }
            return folder.path

    }

        override fun onPostExecute(result: String) {
            super.onPostExecute(result)

            if(result.isNotEmpty()){
                //implement an interface or do something
                Log.d("onPostExecuteSuccess", result)
            }else{
                Log.d("onPostExecuteFailure", result)
            }
        }

    }

물론 위의 API 23 이상의 Android를 사용하고 있다면 장치 메모리에 쓰기를 허용하는 요청을 처리해야 한다.이런 거.

    import android.Manifest
    import android.content.Context
    import android.content.pm.PackageManager
    import android.os.Build
    import androidx.appcompat.app.AppCompatActivity
    import androidx.core.app.ActivityCompat
    import androidx.core.content.ContextCompat

    class ReadandWrite {
        private val mREAD = 9
        private val mWRITE = 10
        private var readAndWrite: Boolean = false
        fun readAndwriteStorage(ctx: Context, atividade: AppCompatActivity): Boolean {
            if (Build.VERSION.SDK_INT < 23) {
                readAndWrite = true
            } else {
                val mRead = ContextCompat.checkSelfPermission(ctx, Manifest.permission.READ_EXTERNAL_STORAGE)
                val mWrite = ContextCompat.checkSelfPermission(ctx, Manifest.permission.WRITE_EXTERNAL_STORAGE)

                if (mRead != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(atividade, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), mREAD)
                } else {
                    readAndWrite = true
                }

                if (mWrite != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(atividade, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), mWRITE)
                } else {
                    readAndWrite = true
                }
            }
            return readAndWrite
        }
    }

그 다음, 어떤 활동에서, 전화를 실행하라.

  var pathToFileCreated = ""
    val anRW = ReadandWrite().readAndwriteStorage(this,this)
    if(anRW){
        pathToFileCreated =  WriteFile().execute("onTaskComplete").get()
        Log.d("pathToFileCreated",pathToFileCreated)
    }

코틀린

class FileReadWriteService {

    private var context:Context? = ContextHolder.instance.appContext

    fun writeFileOnInternalStorage(fileKey: String, sBody: String) {
        val file = File(context?.filesDir, "files")
        try {
            if (!file.exists()) {
                file.mkdir()
            }
            val fileToWrite = File(file, fileKey)
            val writer = FileWriter(fileToWrite)
            writer.append(sBody)
            writer.flush()
            writer.close()
        } catch (e: Exception) {
            Logger.e(classTag, e)
        }
    }

    fun readFileOnInternalStorage(fileKey: String): String {
        val file = File(context?.filesDir, "files")
        var ret = ""
        try {
            if (!file.exists()) {
                return ret
            }
            val fileToRead = File(file, fileKey)
            val reader = FileReader(fileToRead)
            ret = reader.readText()
            reader.close()
        } catch (e: Exception) {
            Logger.e(classTag, e)
        }
        return ret
    }
}

이 코드를 사용하여 파일에 문자열을 쓸 수 있다.

public static void writeTextToFile(final String filename, final String data) {
    File file = new File(filename);
    try {
        FileOutputStream stream = new FileOutputStream(file);
        stream.write(data.getBytes());
        stream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

그렇다면 메인 코드에서는 이를 예를 들어 사용한다.

writeTextToFile(getExternalFilesDir("/").getAbsolutePath() + "/output.txt", "my-example-text");

그런 다음 다음 다음에서 파일을 확인하십시오.Android/data/<package-name>/files.

코틀린의 텍스트 파일에 추가하는 가장 쉬운 방법:

val directory = File(context.filesDir, "LogsToSendToNextMunich").apply { 
    mkdirs() 
}
val file = File(directory,"Logs.txt")
file.appendText("You new text")

파일에만 쓰려면:

yourFile.writeText("You new text")

바이트를 사용하여 파일에 아무거나 쓰기:

FileOutputStream(file).use {
    it.write("Some text for example".encodeToByteArray()) 
}

참조URL: https://stackoverflow.com/questions/14376807/read-write-string-from-to-a-file-in-android

반응형