ファイルを作成し、それにデータを書き込み、Android上でファイルからデータを読み取るにはどうすればいいですか?可能であれば、コードスニペットを提供してください。Androidでファイルを作成する方法は?
答えて
From here: http://www.anddev.org/working_with_files-t115.html
//Writing a file...
try {
// catches IOException below
final String TESTSTRING = new String("Hello Android");
/* We have to use the openFileOutput()-method
* the ActivityContext provides, to
* protect your file from others and
* This is done for security-reasons.
* We chose MODE_WORLD_READABLE, because
* we have nothing to hide in our file */
FileOutputStream fOut = openFileOutput("samplefile.txt",
MODE_PRIVATE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
// Write the string to the file
osw.write(TESTSTRING);
/* ensure that everything is
* really written out and close */
osw.flush();
osw.close();
//Reading the file back...
/* We have to use the openFileInput()-method
* the ActivityContext provides.
* Again for security reasons with
* openFileInput(...) */
FileInputStream fIn = openFileInput("samplefile.txt");
InputStreamReader isr = new InputStreamReader(fIn);
/* Prepare a char-Array that will
* hold the chars we read back in. */
char[] inputBuffer = new char[TESTSTRING.length()];
// Fill the Buffer with data from the file
isr.read(inputBuffer);
// Transform the chars to a String
String readString = new String(inputBuffer);
// Check if we read back the same chars that we had written out
boolean isTheSame = TESTSTRING.equals(readString);
Log.i("File Reading stuff", "success = " + isTheSame);
} catch (IOException ioe)
{ioe.printStackTrace();}
ファイルはどこに書き込まれますか? –
"/data/data/your_project_package_structure/files/samplefile.txt" – Petar
'close'の前に' flush'を呼び出す必要がありますか? –
私はバイトを記述するための一時ファイルを作成するには、次のコードを使用していました。そして、それはうまく動作します。
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "test.txt");
file.createNewFile();
byte[] data1={1,1,0,0};
//write the bytes in file
if(file.exists())
{
OutputStream fo = new FileOutputStream(file);
fo.write(data1);
fo.close();
System.out.println("file created: "+file);
url = upload.upload(file);
}
//deleting the file
file.delete();
System.out.println("file deleted");
私はこのスレッドから他の人に役立つかもしれないクラスを書くことに決めました。これは現在、 "files"ディレクトリにのみ書き込むことを意図していることに注意してください(例えば、 "sdcard"パスに書き込まない)。ファイルtest.txtのに
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.content.Context;
public class AndroidFileFunctions {
public static String getFileValue(String fileName, Context context) {
try {
StringBuffer outStringBuf = new StringBuffer();
String inputLine = "";
/*
* We have to use the openFileInput()-method the ActivityContext
* provides. Again for security reasons with openFileInput(...)
*/
FileInputStream fIn = context.openFileInput(fileName);
InputStreamReader isr = new InputStreamReader(fIn);
BufferedReader inBuff = new BufferedReader(isr);
while ((inputLine = inBuff.readLine()) != null) {
outStringBuf.append(inputLine);
outStringBuf.append("\n");
}
inBuff.close();
return outStringBuf.toString();
} catch (IOException e) {
return null;
}
}
public static boolean appendFileValue(String fileName, String value,
Context context) {
return writeToFile(fileName, value, context, Context.MODE_APPEND);
}
public static boolean setFileValue(String fileName, String value,
Context context) {
return writeToFile(fileName, value, context,
Context.MODE_WORLD_READABLE);
}
public static boolean writeToFile(String fileName, String value,
Context context, int writeOrAppendMode) {
// just make sure it's one of the modes we support
if (writeOrAppendMode != Context.MODE_WORLD_READABLE
&& writeOrAppendMode != Context.MODE_WORLD_WRITEABLE
&& writeOrAppendMode != Context.MODE_APPEND) {
return false;
}
try {
/*
* We have to use the openFileOutput()-method the ActivityContext
* provides, to protect your file from others and This is done for
* security-reasons. We chose MODE_WORLD_READABLE, because we have
* nothing to hide in our file
*/
FileOutputStream fOut = context.openFileOutput(fileName,
writeOrAppendMode);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
// Write the string to the file
osw.write(value);
// save and close
osw.flush();
osw.close();
} catch (IOException e) {
return false;
}
return true;
}
public static void deleteFile(String fileName, Context context) {
context.deleteFile(fileName);
}
}
私はあなたのコードをチェックしましたが、新しいAPI(17)で廃止予定のコマンドがいくつかあります:Context.MODE_WORLD_READABLEとContext.MODE_WORLD_WRITEABLEを変更する必要があります。 –
廃止されたビットとは別に、最後に閉じる必要があり、閉じる前にフラッシュする必要はありません。ちょっとしたコードを投稿しないでください –
書き込み:
String filepath ="/mnt/sdcard/test.txt";
FileInputStream fis = null;
try {
fis = new FileInputStream(filepath);
int length = (int) new File(filepath).length();
byte[] buffer = new byte[length];
fis.read(buffer, 0, length);
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(fis != null)
fis.close();
}
注:AndroidManifestにこれら二つのパーミッションを追加することを忘れないでください
String filepath ="/mnt/sdcard/test.txt";
FileOutputStream fos = null;
try {
fos = new FileOutputStream(filepath);
byte[] buffer = "This will be writtent in test.txt".getBytes();
fos.write(buffer, 0, buffer.length);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(fos != null)
fos.close();
}
読むファイルtest.txtのから。 xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
- 1. AndroidでKMLファイルを作成する方法は?
- 2. Android用.apkファイルの作成方法
- 3. Androidでカスタムプログレスバーを作成する方法
- 4. Androidでアドオンシステムを作成する方法
- 5. Androidでスプライトを作成する方法
- 6. androidでopensslを作成する方法
- 7. Androidでリストビューフィルタを作成する方法
- 8. ファイルを作成してtmpファイル名を作成する方法
- 9. Android - XMLファイルのデータへのリンクを作成する方法
- 10. Android:カスタムボタンウィジェットを作成する方法
- 11. iPhone、iPad、Androidで動作するExtjsアプリケーションの作成方法は?
- 12. AndroidでZIPファイルを作成する
- 13. Androidでjarファイルを作成する
- 14. Androidデバイスでファイルを作成する
- 15. Eclipseでdrawable layer-listをandroidで作成する方法は?
- 16. java(フォルダではない)でファイルを作成する方法は?
- 17. Androidで丸みのあるTextViewを作成する方法は?
- 18. AndroidスタジオでAndroidサンプルプロジェクトを作成する方法
- 19. Androidでフラグメント用のチューザを作成する方法は?
- 20. Androidでナンバーカウンターを作成する方法は?
- 21. AndroidでSpreadSheetの種類のディスプレイを作成する方法は?
- 22. Androidでチャット画面を作成する方法は?
- 23. Android 4.0でタブ付きレイアウトを作成する方法は?
- 24. Android Studioで新しいプロジェクトを作成する方法は?
- 25. Androidアプリケーションでタッチ可能なグラフィカルオブジェクトを作成する方法は?
- 26. Androidアプリケーションで残量を作成/設定する方法は?
- 27. Androidでスライドレイアウトアニメーションを作成する方法は?
- 28. Androidでタイトル付きボーダーを作成する方法は?
- 29. Eclipse Androidでリンク先フォルダを作成する方法は?
- 30. Androidで「フローティングテキストビュー」を作成する方法は?
この[link](http://www.anddev.org/worki ng_with_files-t115.html)これは、ファイルへの書き込みと読み取りの方法に関する簡単なチュートリアルを含んでいます。 – Prashast
http://developer.android.com/training/basics/data-storage/files.html –