android 创建写入txt文件 到SD卡
时间: 2023-06-09 12:05:01 浏览: 175
你可以使用以下代码创建并写入文本文件到SD卡中:
```
try {
File file = new File(Environment.getExternalStorageDirectory(), "filename.txt");
FileWriter writer = new FileWriter(file);
writer.append("Text content to write in file");
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
```
在代码中,我们在SD卡根目录下创建一个名为"filename.txt"的文件,并在其中写入文本内容,你可以根据自己的需要修改文件路径以及文件名。
相关问题
在Android中存储txt文件到sd卡,以当前时间为文件名
您可以使用以下代码将txt文件存储到Android设备的SD卡中,并以当前时间为文件名:
```java
// 获取SD卡目录
String sdCard = Environment.getExternalStorageDirectory().toString();
// 获取当前时间
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
// 创建文件名
String fileName = "file_" + timeStamp + ".txt";
// 创建文件路径
String filePath = sdCard + "/" + fileName;
try {
// 创建文件输出流
FileOutputStream fos = new FileOutputStream(filePath);
// 将文本写入文件
String text = "这是要写入文件的文本";
fos.write(text.getBytes());
// 关闭文件输出流
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
```
请注意,您需要在AndroidManifest.xml文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![7z](https://img-home.csdnimg.cn/images/20241231044736.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)