java 复制文件小结
1,复制固定文件到某个目录
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
// 复制文件后,给文件重命名,带时间戳 public static void addFileTime() throws Exception { String recordtime = ""; Date dt = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); recordtime = sdf.format(dt); System.out.println("recordtime = " +recordtime); // 复制文件后,在文件名后加日期 File dstFile = new File("E:\\testfile\\copyto\\csvTest_"+recordtime+".zip"); //此处recordtime还可以用System.currentTimeMillis() if(!dstFile.exists()) { dstFile.createNewFile(); } File srcFile = new File("E:\\testfile\\csvTest.zip"); copyfile(dstFile, srcFile); } /** * 复制固定文件 ---- 在线采集复制固定的告警到告警服务器目录 * * @return */ public static void copyfile(File dtsFile,File srcFile) { InputStream inStream = null; OutputStream outStream=null; try { outStream = new FileOutputStream(dtsFile); inStream = new FileInputStream(srcFile); byte b[] = new byte[1024]; int n; try { while((n=inStream.read(b))!=-1) { outStream.write(b,0,n); } }catch (IOException e) { e.printStackTrace(); } }catch (IOException e) { e.printStackTrace(); }finally { try { outStream.flush(); outStream.close(); inStream.close(); } catch (IOException e2) { e2.printStackTrace(); } } }
2,复制随机文件到某个目录
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/** * 随机复制文件到某个目录 * * @return */ public static void copyFile_random(String rootPath,String copyToPath) throws Exception{ File rootPathFile = new File(rootPath); File copyToPathFile = new File(copyToPath); if(!rootPathFile.exists()) { System.out.println(rootPath + "目录不存在"); return; } if(!copyToPathFile.exists()) { boolean b = copyToPathFile.mkdirs(); //创建目录 if(!b) { System.err.println(copyToPath+"创建目录失败"); return; // 创建目录失败直接返回 } } File[] txtFiles = rootPathFile.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { // TODO Auto-generated method stub if(name.toLowerCase().endsWith("xlsx")) { return true; } return false; } }); if(txtFiles!=null) { Random r = new Random(); int i = r.nextInt(txtFiles.length); File copyFile = txtFiles[i]; System.out.println( "i===="+ i); File newFile = new File(copyToPath +"\\"+System.currentTimeMillis()+"_" +copyFile.getName()); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(copyFile),"UTF-8")); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(newFile),"UTF-8")); String tmp = null; while(true) { tmp = br.readLine(); if(tmp==null) { break; } bw.write(tmp); bw.write("\n"); //写入换行符 } if(bw!=null) { bw.flush(); bw.close(); } if(br!=null) { br.close(); } System.out.println("操作执行完毕"); } }
3,使用shell命令复制文件到linux机器目录
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
private static String DEFAULTCHART = "UTF-8"; public static void main(String[] args) throws Exception { addAlarmFile_new(""); } /** * shell指令复制文件到linux机器 * * */ public static void addAlarmFile_new(String collectionServiceIP) throws Exception{ String recordtime = ""; Date dt = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); recordtime = sdf.format(dt); System.out.println("recordtime = " +recordtime); int port = 22; String username = "root"; String password = "Changeme_123"; // 创建连接 Connection conn = new Connection(collectionServiceIP,port); conn.connect(); // 验证用户名密码 conn.authenticateWithPassword(username,password); // 进入到文件保存的目录alarm Session session = conn.openSession(); session.execCommand("cd opt/osss/share/NCE/FMServices/export/fileint/alarm/;ls"); // 消费所有输入流 String inStr = consumeInputStream(session.getStdout()); consumeInputStream1(session.getStderr()); session.close(); // 将文件从alarm复制到fm目录下 Session session1 = conn.openSession(); session1.execCommand("cp /cd opt/osss/share/NCE/FMServices/export/fileint/alarm/"+inStr+" /opt/osss/share/NCE/FMServices/export/fileint/fm/;"); consumeInputStream1(session1.getStdout()); consumeInputStream1(session1.getStderr()); session1.close(); // 修改文件权限和群组 Session session2 = conn.openSession(); session2.execCommand("chown -R ossuser:ossgroup /opt/osss/share/NCE/FMServices/export/fileint/fm/"); session2.close(); // 查看复制过去文件的信息 // # stat testfile #输入命令 // File: `testfile' // Size: 102 Blocks: 8 IO Block: 4096 regular file // Size和Block之前的字符串就是文件大小 // Device: 807h/2055d Inode: 1265161 Links: 1 // Access: (0644/-rw-r--r--) Uid: ( 0/ root) Gid: ( 0/ root) // Access: 2014-08-13 14:07:20.000000000 +0800 // Modify: 2014-08-13 14:07:07.000000000 +0800 // Change: 2014-08-13 14:07:07.000000000 +0800 String res = doShellCode(collectionServiceIP,"stat /opt/osss/share/NCE/FMServices/export/fileint/fm/"+inStr); System.out.println("res====="+res); // 记录复制过去的文件 String zipSize = getZipSize(res); System.out.println("复制后文件"+inStr + "\n 大小:"+ zipSize); tools.writeText("复制文件成功,文件大小为:" + zipSize, false); conn.close(); } private static java.lang.String getZipSize(java.lang.String shellResult) { if(shellResult==null||shellResult.equals("")) { System.out.println("传入查看文件大小的命令有问题"); return null; } int startIndex = shellResult.indexOf("Size:"); int endIndex = shellResult.indexOf("Blocks:"); String ress = shellResult.substring(startIndex+5,endIndex); //此处如果不+5,返回值就是“Size: 102”;+5之后,返回值就是“102” return ress; } public static String doShellCode(String collectionServiceIP,String ShellCode) throws Exception { int port = 22; String username = "root"; String password = "Changeme_123"; // 创建连接 Connection conn = new Connection(collectionServiceIP,port); conn.connect(); // 验证用户名密码 conn.authenticateWithPassword(username,password); Session session = conn.openSession(); session.execCommand(ShellCode); // 消费所有输入流 // String inStr = consumeInputStream(session.getStdout()); String errStr = consumeInputStream(session.getStderr()); String result = processStdout(session.getStdout(),DEFAULTCHART); session.close(); return result; } private static String processStdout(InputStream in, String charset){ InputStream stdout = new StreamGobbler(in); StringBuffer buffer = new StringBuffer(); try { BufferedReader br = new BufferedReader(new InputStreamReader(stdout,charset)); String line=null; while((line=br.readLine()) != null){ buffer.append(line+"\n"); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return buffer.toString(); } /** * 消费inputstream,并返回 * @throws Exception */ public static void consumeInputStream1(InputStream is) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(is)); String s ; while((s=br.readLine())!=null){ System.out.println(s); } } public static String consumeInputStream(InputStream is) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(is)); String s ; StringBuilder sb = new StringBuilder(); ArrayList<String> files = new ArrayList<>(); while((s=br.readLine())!=null){ System.out.println(s); sb.append(s); } return files.get(new Random().nextInt(files.size())); }