티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
Read/Write String from/to a File in Android
Android에서 파일로 문자열 읽기/쓰기
문제 내용
I want to save a file to the internal storage by getting the text inputted from EditText. Then I want the same file to return the inputted text in String form and save it to another String which is to be used later.
EditText에서 입력한 텍스트를 가져와서 내부 저장소에 파일을 저장하고 싶습니다. 그런 다음 같은 파일이 입력된 텍스트를 문자열 형식으로 반환하고 나중에 사용할 다른 문자열에 저장하기를 원합니다.
Here's the code:
코드는 다음과 같습니다:
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);
}
});
}
I have included comments to help you further analyze my points as to where I want the operations to be done/variables to be used.
작업을 수행하려는 위치/사용할 변수에 대해 내 요점을 추가로 분석하는 데 도움이 되는 설명을 포함했습니다.
높은 점수를 받은 Solution
Hope this might be useful to you.
이것이 당신에게 유용할 수 있기를 바랍니다.
Write File:
파일 쓰기:
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());
}
}
Read File:
파일 읽기:
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;
}
가장 최근 달린 Solution
The Kotlin
way by using builtin Extension function on File
파일에 내장된 확장 기능을 이용한 코틀린 방식
Write: yourFile.writeText(textFromEditText)
Read: yourFile.readText()
쓰기: yourFile.writeText(textFromEditText)
읽기: yourFile.readText()
출처 : https://stackoverflow.com/questions/14376807/read-write-string-from-to-a-file-in-android
'개발 > 안드로이드' 카테고리의 다른 글
액티비티 스택에서 액티비티 제거하기 (0) | 2023.01.05 |
---|---|
안드로이드 모바일 웹사이트(어플리케이션이 아닌)에서 WhatsApp으로 링크 공유하기 (0) | 2023.01.05 |
안드로이드에서 파일의 MIME 타입 확인하기 (0) | 2023.01.04 |
인터넷 연결 확인하기 (0) | 2023.01.04 |
탭 호스트 액티비티에서 결과(startActivityForResult) 반환하기 (0) | 2023.01.03 |