简体   繁体   English

Java随机移动文件

[英]Java move a file randomly

Hi so I'm working on an app and at the moment I have code that downloads a bunch of zip files to /sdcard/RAND I have it get all the files into a string array and now i want to move one of those zips randomly to /sdcard/RAND/use my app then will always go to that folder and use that zip when the app is opened. 嗨,我正在开发一个应用程序,此刻我有将一堆zip文件下载到/ sdcard / RAND的代码,将所有文件都放入一个字符串数组中,现在我想随机移动其中一个zip文件到/ sdcard / RAND /使用我的应用程序,那么在打开应用程序时,它将始终转到该文件夹​​并使用该zip。 It's to keep the app interesting since each of the zips do something differently. 这是为了保持应用程序的趣味性,因为每个zip的功能都不同。 Thanks for any help on how I can then move it randomly. 感谢您提供有关如何随机移动它的帮助。

package com.android.rand;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;

public class Main extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        List<String> w = new ArrayList<String>();
        String[] a;
        File f = new File("/mnt/sdcard/RAND");
        for (File s : f.listFiles()) {
            w.add(f.toString());
        }

        a = new String[w.size()];
        a = w.toArray(a);
    }

}

Since you have the file names in a string array, why not generate a random number between 0 and length-1, use that as the index into the array, grab that file name and move it. 由于文件名在字符串数组中,因此为什么不生成介于0和length-1之间的随机数,请将其用作数组的索引,获取该文件名并将其移动。 Would that work? 那行得通吗?

For example 例如

Random rand = new Random();
String path = a[rand.nextInt(a.length)]; 
//note, I used length not length-1 here because of how nextInt works

//move the file indicated by "path"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM