在Android中创建文件有以下几种方法:
- 使用FileOutputStream类创建文件
try {
FileOutputStream fileOutputStream = openFileOutput("filename.txt", Context.MODE_PRIVATE);
String content = "This is the content of the file";
fileOutputStream.write(content.getBytes());
fileOutputStream.close();
Toast.makeText(this, "File created successfully", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
- 使用BufferedWriter类创建文件
try {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("filename.txt"));
bufferedWriter.write("This is the content of the file");
bufferedWriter.close();
Toast.makeText(this, "File created successfully", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
- 使用File类创建文件
File file = new File(getFilesDir(), "filename.txt");
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
String content = "This is the content of the file";
fileOutputStream.write(content.getBytes());
fileOutputStream.close();
Toast.makeText(this, "File created successfully", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
注意:在使用以上三种方法创建文件时,需要在AndroidManifest.xml文件中添加WRITE_EXTERNAL_STORAGE权限。
在Android中创建文件有多种方式,以下是其中几种:
- 使用File类创建文件:
File file = new File(Environment.getExternalStorageDirectory(), "filename.txt"); //在SD卡根目录下创建文件
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
- 使用FileOutputStream类创建文件:
String content = "Hello World!";
try {
FileOutputStream fos = openFileOutput("filename.txt", Context.MODE_PRIVATE);
fos.write(content.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
- 使用FileWriter类创建文件:
String content = "Hello World!";
try {
FileWriter fw = new FileWriter("filename.txt");
fw.write(content);
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
- 使用BufferedWriter类创建文件:
String content = "Hello World!";
try {
BufferedWriter bw = new BufferedWriter(new FileWriter("filename.txt"));
bw.write(content);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
- 使用PrintWriter类创建文件:
String content = "Hello World!";
try {
PrintWriter pw = new PrintWriter("filename.txt");
pw.print(content);
pw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
以上方法都可以用来创建文件,具体使用哪种方法可以根据实际情况需求选择。
发布者:luotuoemo,转转请注明出处:https://www.jintuiyun.com/116811.html