android中把文件保存到sdcard代码实例

时间:2021-08-09 03:00:32

直接上代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.example.test;
 
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
 
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.widget.Toast;
 
public class MainActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
    //要保存的文件名和文件内容
    String fileName = "test.txt";
    String content = "This is a test.";
    
    //判断sdcard是否存在
    String state = Environment.getExternalStorageState();
    if(state.equals(Environment.MEDIA_MOUNTED)) {
     //获取SDCard目录
     File sdcardPath = Environment.getExternalStorageDirectory();
     
     File file = new File(sdcardPath, fileName);
     FileOutputStream fos;
  try {
  fos = new FileOutputStream(file);
  fos.write(content.getBytes());
  fos.close();
  } catch (FileNotFoundException e) {
  e.printStackTrace();
  } catch (IOException e) {
  e.printStackTrace();
  }
  Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
    } else {
     Toast.makeText(this, "sdcard不存在获取不可写入", Toast.LENGTH_SHORT).show();
    }
    
  }
}