String filename = "myfile"; String fileContents = "Hello world!"; try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) { fos.write(fileContents.getBytes()); }怎么在指定的文件夹下创建文件
时间: 2024-02-25 20:58:26 浏览: 170
要在指定的文件夹下创建文件,你需要指定完整的文件路径,包括文件夹路径和文件名。可以使用Java的File类来实现。以下是一个例子:
```java
String folderPath = "/sdcard/myfolder/"; // 文件夹路径
String filename = "myfile.txt"; // 文件名
String fileContents = "Hello world!"; // 文件内容
File folder = new File(folderPath);
if (!folder.exists()) { // 如果文件夹不存在,则创建
folder.mkdirs();
}
File file = new File(folder, filename);
try (FileOutputStream fos = new FileOutputStream(file)) {
fos.write(fileContents.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
```
在这个例子中,首先指定了文件夹路径和文件名。然后使用File类创建文件夹和文件对象。如果文件夹不存在,则创建。最后使用FileOutputStream写入文件内容。注意,为了避免权限问题,建议将文件夹路径指定在应用私有目录下,例如:`context.getFilesDir().getAbsolutePath() + "/myfolder/"`。
阅读全文
相关推荐













