How to write into the USB (External storage)

佐手、 提交于 2021-01-28 11:53:47

问题


I am trying to copy a file from my computer to USB in java. The problem is, the code creates a file on the Usb but the content of the file is not copied from source to destination(computer to usb). How can i do that? I want the filename R.java to be copied into the usb as system.txt.

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 R {

private static File to;

public static void main(String[] args) {
    // current working dir where there is file u want to replicate
    File f = new File("." + "/R.java");

    // destination location
    File so = new File("/media");
    for (File s : so.listFiles()) {
        String r = s.getName();
        to = new File("/media/" + r + "/system.txt");
        if (!to.exists()) {
            try {
                to.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                System.out
                        .print(to.getName() + " " + e.getMessage() + "\n");
            }
        }
            if (f.exists()) {
                FileChannel is = null;
                FileChannel os = null;
                try {
                    is = new FileInputStream(f).getChannel();
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                try {
                    os = new FileOutputStream(to).getChannel();
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                try {
                    os.transferFrom(is, 0, is.size());
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

 }

I am on LINUX machine

来源:https://stackoverflow.com/questions/32147983/how-to-write-into-the-usb-external-storage

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!