Java 如何重命名现有文件?
所以在我用MediaRecorder录制了一些东西并把它放在android设备的某个地方之后。然后如何重命名该文件?这是我找到的最接近解决方案。我点击按钮后,什么也没发生Java 如何重命名现有文件?,java,android,eclipse,Java,Android,Eclipse,所以在我用MediaRecorder录制了一些东西并把它放在android设备的某个地方之后。然后如何重命名该文件?这是我找到的最接近解决方案。我点击按钮后,什么也没发生 public void nameAlert() { AlertDialog.Builder nameAlert = new AlertDialog.Builder(this); nameAlert.setMessage("Name of your recorded file:"); final Edit
public void nameAlert() {
AlertDialog.Builder nameAlert = new AlertDialog.Builder(this);
nameAlert.setMessage("Name of your recorded file:");
final EditText input = new EditText(this);
nameAlert.setView(input);
nameAlert.setPositiveButton("Enter", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
newFileName = input.getText();
String currentFileName = externalStoragePath;
currentFileName = currentFileName.substring(1);
Log.i(storagePath, currentFileName);
File directory = new File (externalStoragePath);
File from = new File (directory, currentFileName);
File to = new File (directory, newFileName + ".mp3");
from.renameTo(to);
}
});
nameAlert.show();
此外,这可能是相关的
externalStoragePath = Environment.getExternalStorageDirectory().getAbsolutePath();
日志:
根据参考资料。许多失败是可能的。一些更可能的故障包括:
你能逐一核对一下吗?我想你可以知道发生了什么。首先检查文件是否被激活: 如果它仍然不起作用,就必须手工操作
if(to.exists()) throw new java.IOException("file exists");
if (from.renameTo(to)) {
//success
}else{
to.createNewFile();
FileChannel FCfrom = null;
FileChannel FCto = null;
try {
FCfrom = new FileInputStream(from).getChannel();
FCto = new FileOutputStream(to).getChannel();
long count = 0;
long size = source.size();
while((count += destination.transferFrom(source, count, size-count))<size);
}finally {
if(FCto != null){
FCto.close();
FCfrom.close();
from.delete();
}
}
if(to.exists())抛出新的java.IOException(“文件存在”);
如果(从重命名到){
//成功
}否则{
to.createNewFile();
FileChannel FCfrom=null;
FileChannel FCto=null;
试一试{
FCfrom=新文件输入流(from).getChannel();
FCto=新文件输出流(to).getChannel();
长计数=0;
long size=source.size();
虽然((count+=destination.transferFrom(source,count,size count))我找到了答案!问题出在这一行:
File directory = new File (externalStoragePath);
我把它改成这样:
File directory = new File (externalStoragePath + File.separator + "/Android/data/com.whizzappseasyvoicenotepad/");
因为externalStoragePath返回整个路径(包括文件名)您的代码非常简单。@SmartLemon知道可能有什么问题吗?onclick的代码在哪里?@SmartLemon我编辑了原始日志显示了警报对话框吗?抱歉,但我一秒钟前才发现:)无论如何,谢谢你,伙计!我刚想出来,没有失败,检查我的答案,无论如何,谢谢你!
File directory = new File (externalStoragePath + File.separator + "/Android/data/com.whizzappseasyvoicenotepad/");