Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在Android中一次性复制文件?不创建几十行代码!样品中的Smth_Java_Android - Fatal编程技术网

Java 如何在Android中一次性复制文件?不创建几十行代码!样品中的Smth

Java 如何在Android中一次性复制文件?不创建几十行代码!样品中的Smth,java,android,Java,Android,我需要把文件从一个地方复制到另一个地方。我找到了很好的解决办法: import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class FileCopyTest { public static void main(String[] args) { Path source = Paths.get("/Users/

我需要把文件从一个地方复制到另一个地方。我找到了很好的解决办法:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileCopyTest {
public static void main(String[] args) {
    Path source = Paths.get("/Users/apple/Desktop/test.rtf");
    Path destination = Paths.get("/Users/apple/Desktop/copied.rtf");

    try {
        Files.copy(source, destination);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}
这个库工作得很好,但在Android中不可用

我试着找出我应该用哪种方式来代替,但它没有任何建议。。。我几乎可以肯定,它应该是一个允许一次性复制文件的库

如果有人知道说“请”,我相信这将是非常有帮助的回答为负载的人

谢谢

试试这段代码

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class CopyFile {

public static void main(String[] args) {
    File sourceFile = new File(
            "/Users/Neel/Documents/Workspace/file1.txt");

    File destFile = new File(
            "/Users/Neel/Documents/Workspace/file2.txt");

    /* verify whether file exist in source location */
    if (!sourceFile.exists()) {
        System.out.println("Source File Not Found!");
    }

    /* if file not exist then create one */
    if (!destFile.exists()) {
        try {
            destFile.createNewFile();

            System.out.println("Destination file doesn't exist. Creating   

     one!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    FileChannel source = null;
    FileChannel destination = null;

    try {

        /**
         * getChannel() returns unique FileChannel object associated a file
         * output stream.
         */
        source = new FileInputStream(sourceFile).getChannel();

        destination = new FileOutputStream(destFile).getChannel();

        if (destination != null && source != null) {
            destination.transferFrom(source, 0, source.size());
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    finally {
        if (source != null) {
            try {
                source.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (destination != null) {
            try {
                destination.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    }
    }

使用此实用程序类读取/写入SD卡中的文件:

public class MyFile {

    String TAG = "MyFile";
    Context context;
    public MyFile(Context context){
        this.context = context;
    }

    public Boolean writeToSD(String text){
        Boolean write_successful = false;
         File root=null;  
            try {  
                // check for SDcard   
                root = Environment.getExternalStorageDirectory();  
                Log.i(TAG,"path.." +root.getAbsolutePath());  

                //check sdcard permission  
                if (root.canWrite()){  
                    File fileDir = new File(root.getAbsolutePath());  
                    fileDir.mkdirs();  

                    File file= new File(fileDir, "samplefile.txt");  
                    FileWriter filewriter = new FileWriter(file);  
                    BufferedWriter out = new BufferedWriter(filewriter);  
                    out.write(text);  
                    out.close();  
                    write_successful = true;
                }  
            } catch (IOException e) {  
                Log.e("ERROR:---", "Could not write file to SDCard" + e.getMessage());  
                write_successful = false;
            }  
        return write_successful;
    }

    public String readFromSD(){
        File sdcard = Environment.getExternalStorageDirectory();
        File file = new File(sdcard,"samplefile.txt");
        StringBuilder text = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            String line;
            while ((line = br.readLine()) != null) {
                text.append(line);
                text.append('\n');
            }
        }
        catch (IOException e) {
        }
        return text.toString();
    }

    @SuppressLint("WorldReadableFiles")
    @SuppressWarnings("static-access")
    public Boolean writeToSandBox(String text){
        Boolean write_successful = false;
        try{
            FileOutputStream fOut = context.openFileOutput("samplefile.txt",
                    context.MODE_WORLD_READABLE);
            OutputStreamWriter osw = new OutputStreamWriter(fOut); 
            osw.write(text);
            osw.flush();
            osw.close();
        }catch(Exception e){
            write_successful = false;
        }
        return write_successful;
    }
    public String readFromSandBox(){
        String str ="";
        String new_str = "";
        try{
            FileInputStream fIn = context.openFileInput("samplefile.txt");
            InputStreamReader isr = new InputStreamReader(fIn);
            BufferedReader br=new BufferedReader(isr);

            while((str=br.readLine())!=null)
            {
                new_str +=str;
                System.out.println(new_str);
            }            
        }catch(Exception e)
        {           
        }
        return new_str;
    }
}
注意,您应该在AndroidManifest文件中授予此权限

这里是许可证

uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" 
欲了解更多详情,请访问:

使用commons io,您可以做到这一点

FileInputStream source = null;
FileOutputStream destination = null;
try {
    source = new FileInputStream(new File(/*...*/));
    destination = new FileOutputStream(new File(Environment.getExternalStorageDirectory(), /*...*/);
    IOUtils.copy(source, destination);
} finally {
    IOUtils.closeQuietly(source);
    IOUtils.closeQuietly(destination);
}
加上

compile 'org.apache.directory.studio:org.apache.commons.io:2.4' 

到build.gradle文件

的可能副本如果您只希望指向库的链接为您执行此操作,则这不是堆栈溢出的适当问题。@MikeM。我编辑headerDownvote是因为close在try{中,而不是finally中{。Android中不可用是什么意思?请将其添加到build.gradle依赖项中。如果您希望使用默认可用类,而不管您在最初的帖子中声称什么,显然不是库,那么只需执行commons io在包含它时所做的操作。尽管请注意,写入Environment.getExternalStorageDirectory自Android 6.0以来需要运行时权限+