一些常用功能总结

1.InputStream转String

public String downloadFile(CommonsMultipartFile testfile) throws IOException {

String filecontent = "";

if (testfile != null && !testfile.isEmpty()) {// 如果有文章中带有附件

String filename = testfile.getOriginalFilename();

InputStream is = null;// 附件输入流

try {

is = testfile.getInputStream();

System.out.println("is length:"+is.available());

BufferedReader reader = new BufferedReader(new InputStreamReader(is));      

StringBuilder sb = new StringBuilder();      

 String line = null;      

 while ((line = reader.readLine()) != null) {      

sb.append(line + " ");      

}   

filecontent = sb.toString();

System.out.println("filecontent:"+filecontent);

} catch (IOException exception) {

exception.printStackTrace();

} finally {

if (is != null) {

is.close();

}

}

return filecontent;

}

return filecontent;

}

2.文件上传:

vm文件:

 <label class="form-labeler control-label">测试部署单</label> 

                    <div class="form-content" method="post" >   

<input id="oaFile" name="file" type="file"  style="margin:10px;">

</div>

form表单中增加:

<form id="form" name="form" class="form-horizontal" method="post" action="setOddiffJob.htm" enctype="multipart/form-data" >

controller:

上传文件:

public String downloadFile(CommonsMultipartFile testfile,String destDir) throws IOException {

String filecontent = "";

if (testfile != null && !testfile.isEmpty()) {// 如果有文章中带有附件

String filename = testfile.getOriginalFilename();

System.out.println("filename:" + filename);

filecontent = destfileDir + filename;

DataOutputStream out = new DataOutputStream(new FileOutputStream(filecontent));// 存放文件的绝对路径

InputStream is = null;// 附件输入流

try {

is = testfile.getInputStream();

byte[] b=new byte[is.available()];
     is.read(b);
     out.write(b);
   

}   

filecontent = sb.toString();

System.out.println("filecontent:"+filecontent);

} catch (IOException exception) {

exception.printStackTrace();

} finally {

if (is != null) {

is.close();

}

if (out != null) {

out.close();

}

}

return filecontent;

}

return filecontent;

}

@RequestMapping(value = "/tool/setOddiffJob")

public String setOddiffJob(@RequestParam("file") CommonsMultipartFile[] files, HttpServletRequest request,

Model model) throws Exception {

String onlineFile = downloadFile(files[0]);//按顺序读取文件

request.getParameter("appName");//读取表单中其他元素

}

3.java运行scp命令:

Connection conn = new Connection("10.218.146.27");

conn.connect();

conn.authenticateWithPassword("name", "passwd");//设置用户名和密码

// 建立SCP客户端

SCPClient scpClient = conn.createSCPClient();

// 将本地文件上传到服务器端的目录下

String onlinedestDir = "/home/admin";

File onlineDestDir = new File(onlinedestDir);

if(!onlineDestDir.isDirectory()){//判断路径是否存在,不存在就创建

onlineDestDir.mkdir();

}

scpClient.put(onlineFile, onlinedestDir);//上传文件到远程服务器

conn.close();

原文地址:https://www.cnblogs.com/aiwa/p/6209662.html