在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);
}
});
}

我已经包括了评论,以帮助您进一步分析我的观点,即我希望在哪里执行操作/使用变量。

618646 次浏览

检查下面的代码。

从文件系统中的文件读取。

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;
}
}

我想这对你有帮助。

希望这对你有用。

写文件:

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;
}
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();
}

对于那些寻找读取和写入字符串到文件的一般策略的人:

首先,获取一个文件对象

您需要存储路径。对于内部存储,使用:

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();
}

或者用谷歌番石榴

字符串内容=文件。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);

或者如果你用谷歌番石榴

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

为了完整起见,我要提一下

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

它不需要库,但基准测试比其他选项慢50% - 400%(在我的Nexus 5上的各种测试中)。

笔记

对于这些策略,您将被要求捕获IOException。

Android上默认的字符编码是UTF-8。

如果你使用外部存储,你需要添加到你的清单:

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

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

写权限意味着读权限,所以不需要两者兼备。

只是对从文件方法读取字符串进行了一些修改,以获得更好的性能

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;
}

我是一个初学者,努力让这个工作今天。

下面是我最终选择的类。它起作用了,但我想知道我的解决方案有多不完美。不管怎样,我希望你们中一些更有经验的人可能愿意看看我的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();
}
}
}

我们需要的第一件事是AndroidManifest.xml中的权限

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

所以在asyncTask Kotlin类中,我们处理文件的创建

    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
}
}

Kotlin的方法是在File上使用内置扩展函数

写: yourFile.writeText(textFromEditText)
读:< /强> yourFile.readText()

在kotlin中添加文本文件最简单的方法:

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())
}

我们可以使用这段代码将String写入文件

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();
}
}

然后在Main代码中,我们使用这个

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

之后,检查Android/data/<package-name>/files的文件。