android,如何重命名文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10424997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
android, How to rename a file?
提问by Hesam
In my application, I need to record video. Before start of recording in I'm assigning a name and directory to it. After recording is finished user has ability to rename his file. I wrote following code but seem it doesn't work.
在我的应用程序中,我需要录制视频。在开始录制之前,我正在为其分配一个名称和目录。录制完成后,用户可以重命名他的文件。我写了以下代码,但似乎不起作用。
When user enters name of file and click on button I'll do this:
当用户输入文件名并单击按钮时,我将执行以下操作:
private void setFileName(String text) {
String currentFileName = videoURI.substring(videoURI.lastIndexOf("/"), videoURI.length());
currentFileName = currentFileName.substring(1);
Log.i("Current file name", currentFileName);
File directory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES), MEDIA_NAME);
File from = new File(directory, "currentFileName");
File to = new File(directory, text.trim() + ".mp4");
from.renameTo(to);
Log.i("Directory is", directory.toString());
Log.i("Default path is", videoURI.toString());
Log.i("From path is", from.toString());
Log.i("To path is", to.toString());
}
Text: is the name which is entered by user. Current Filename: is the name which is assigned by me before recording MEDIA_NAME: name of folder
文本:是用户输入的名称。当前文件名:是我在录制前分配的名称 MEDIA_NAME:文件夹名称
Logcat shows this:
Logcat 显示了这一点:
05-03 11:56:37.295: I/Current file name(12866): Mania-Karaoke_20120503_115528.mp4
05-03 11:56:37.295: I/Directory is(12866): /mnt/sdcard/Movies/Mania-Karaoke
05-03 11:56:37.295: I/Default path is(12866): /mnt/sdcard/Movies/Mania-Karaoke/Mania-Karaoke_20120503_115528.mp4
05-03 11:56:37.295: I/From path is(12866): /mnt/sdcard/Movies/Mania-Karaoke/currentFileName
05-03 11:56:37.295: I/To path is(12866): /mnt/sdcard/Movies/Mania-Karaoke/hesam.mp4
Any suggestion would be appreciated.
任何建议将不胜感激。
采纳答案by COD3BOY
The problem is in this line,
问题出在这一行,
File from = new File(directory, "currentFileName");
Here currentFileName
is actually a String you dont have to use "
这currentFileName
实际上是一个你不必使用的字符串"
try it this way,
试试这个方法
File from = new File(directory, currentFileName );
^ ^ //You dont need quotes
回答by Niranjan
In your code:
在您的代码中:
Shouldn't it be :
不应该是:
File from = new File(directory, currentFileName);
File from = new File(directory, currentFileName);
instead of
代替
File from = new File(directory, "currentFileName");
File from = new File(directory, "currentFileName");
For safety,
为了安全,
Use the File.renameTo() . But check for directory existence before renaming it!
使用 File.renameTo() 。但是在重命名之前检查目录是否存在!
File dir = Environment.getExternalStorageDirectory();
if(dir.exists()){
File from = new File(dir,"from.mp4");
File to = new File(dir,"to.mp4");
if(from.exists())
from.renameTo(to);
}
Refer: http://developer.android.com/reference/java/io/File.html#renameTo%28java.io.File%29
参考:http: //developer.android.com/reference/java/io/File.html#renameTo%28java.io.File%29
回答by Thomas Vos
Use this method to rename a file. The file from
will be renamed to to
.
使用此方法重命名文件。该文件from
将重命名为to
.
private boolean rename(File from, File to) {
return from.getParentFile().exists() && from.exists() && from.renameTo(to);
}
Example code:
示例代码:
public class MainActivity extends Activity {
private static final String TAG = "YOUR_TAG";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File currentFile = new File("/sdcard/currentFile.txt");
File newFile = new File("/sdcard/newFile.txt");
if (rename(currentFile, newFile)) {
//Success
Log.i(TAG, "Success");
} else {
//Fail
Log.i(TAG, "Fail");
}
}
private boolean rename(File from, File to) {
return from.getParentFile().exists() && from.exists() && from.renameTo(to);
}
}
回答by taran mahal
/**
* ReName any file
* @param oldName
* @param newName
*/
public static void renameFile(String oldName,String newName){
File dir = Environment.getExternalStorageDirectory();
if(dir.exists()){
File from = new File(dir,oldName);
File to = new File(dir,newName);
if(from.exists())
from.renameTo(to);
}
}
回答by Jawad Zeb
Working example...
工作示例...
File oldFile = new File("your old file name");
File latestname = new File("your new file name");
boolean success = oldFile .renameTo(latestname );
if(success)
System.out.println("file is renamed..");
回答by Krishnakant Dalal
Provide target File object with different file Name.
提供具有不同文件名的目标文件对象。
// Copy the source file to target file.
// In case the dst file does not exist, it is created
void copy(File source, File target) throws IOException {
InputStream in = new FileInputStream(source);
OutputStream out = new FileOutputStream(target);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
回答by Changwei Yao
you should check if the directory exist!
你应该检查目录是否存在!
File directory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES), MEDIA_NAME);
if(!directory.exist()){
directory.mkdirs();
}
回答by Jon
This is what I ended up using. It handles the case where there is an existing file with the same name by adding an integer to the file name.
这就是我最终使用的。它通过向文件名添加整数来处理存在同名文件的情况。
@NonNull
private static File renameFile(@NonNull File from,
@NonNull String toPrefix,
@NonNull String toSuffix) {
File directory = from.getParentFile();
if (!directory.exists()) {
if (directory.mkdir()) {
Log.v(LOG_TAG, "Created directory " + directory.getAbsolutePath());
}
}
File newFile = new File(directory, toPrefix + toSuffix);
for (int i = 1; newFile.exists() && i < Integer.MAX_VALUE; i++) {
newFile = new File(directory, toPrefix + '(' + i + ')' + toSuffix);
}
if (!from.renameTo(newFile)) {
Log.w(LOG_TAG, "Couldn't rename file to " + newFile.getAbsolutePath());
return from;
}
return newFile;
}
回答by twenk11k
public void renameFile(File file,String suffix) {
String ext = FilenameUtils.getExtension(file.getAbsolutePath());
File dir = file.getParentFile();
if(dir.exists()){
File from = new File(dir,file.getName());
String name = file.getName();
int pos = name.lastIndexOf(".");
if (pos > 0) {
name = name.substring(0, pos);
}
File to = new File(dir,name+suffix+"."+ext);
if(from.exists())
from.renameTo(to);
}
}