【问题标题】:Java move a file randomlyJava随机移动文件
【发布时间】:2011-03-06 03:53:46
【问题描述】:

嗨,我正在开发一个应用程序,目前我有将一堆 zip 文件下载到 /sdcard/RAND 的代码,我让它将所有文件放入一个字符串数组中,现在我想移动一个这些 zip 随机到 /sdcard/RAND/use my app 然后将始终转到该文件夹​​并在打开应用程序时使用该 zip。这是为了让应用程序保持有趣,因为每个拉链都有不同的作用。感谢您对我如何随机移动它的任何帮助。

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);
    }

}

【问题讨论】:

    标签: java android string random


    【解决方案1】:

    既然你有一个字符串数组中的文件名,为什么不生成一个介于 0 和 length-1 之间的随机数,将其用作数组的索引,获取该文件名并移动它。这行得通吗?

    例如

    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"
    

    【讨论】:

    • 你能解释一下我如何复制文件吗?我对所有这些东西都很陌生,但我确实需要复制而不是移动它。对不起,我学习的知识如此有限:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-28
    • 1970-01-01
    • 1970-01-01
    • 2017-07-29
    相关资源
    最近更新 更多