如何从Android中的文件读取/写入string

我search了大部分的问题,但都没有解决我的问题。

我想通过从EditTextinput文本保存文件到内部存储。 然后,我想让相同的文件以stringforms返回input的文本,并保存到另一个稍后要使用的string中。

代码如下:

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

我已经包含了一些意见,以帮助您进一步分析我想要完成操作的位置/要使用的variables。

希望这可能对你有用。

写入文件:

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

对于那些寻找读写string文件的一般策略:

首先,获取一个文件对象

你需要存储path。 对于内部存储,请使用:

 File path = context.getFilesDir(); 

对于外部存储(SD卡),请使用:

 File path = context.getExternalFilesDir(null); 

然后创build你的文件对象:

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

写一个string到文件

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

或与谷歌番石榴

 Files.write("text-to-write", file, "UTF-8"); 

将文件读取到一个string

 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%(在Nexus 5的各种testing中)。

笔记

对于这些策略中的每一个,都会被要求捕获一个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(); } 

只需稍加修改就可以从文件方法读取string以获得更好的性能

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

我认为这会帮助你。

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

下面是我结束的课。 它的工作原理,但我想知道我的解决scheme是多么不完美。 无论如何,我希望你们中有些更有经验的人可能愿意看看我的IOclass,给我一些提示。 干杯!

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

附加一个现有的文件。

  File file = new File(persistPath); BufferedWriter out = new BufferedWriter(new FileWriter(file, true), 1024); out.write(str); out.newLine(); out.close();