android新建文件代码,如何在Android中创建文件?

博客给出了一个Android文件操作的类,包含获取文件值、追加文件内容、设置文件值、写入文件和删除文件等功能。代码仅用于写入“files”目录,通过Java的输入输出流和Android的Context类实现,还对写入模式进行了安全检查。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我决定从这个线程写一个可能对其他人有帮助的类。请注意,这目前仅用于写入“files”目录(例如,不写入“sdcard”路径)。

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

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值