Java怎样把文件写入到客户端的硬盘上
展开全部
package test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class Test {
public static void main(String[] args) throws FileNotFoundException {
String source = "hello world!";
String filePath = "c:\\file.txt";
String newFilePath = "c:\\" + System.currentTimeMillis() + ".txt";
saveFile1(source);
saveFile2(filePath, newFilePath);
}
/**
* 直接写入数据
* @param source
* @return
*/
public static boolean saveFile1(String source){
byte buf[] = source.getBytes();
try(FileOutputStream fs = new FileOutputStream("c:\\file.txt")){
for (int i = 0; i < buf.length; i++) {
fs.write(buf[i]);
}
return true;
}catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 读取文件另存为
* @param filePath
* @param newFilePath
* @return
*/
public static boolean saveFile2(String filePath, String newFilePath){
File file = new File(filePath);
if (file.exists() && file.isFile()) {
try (FileInputStream fi = new FileInputStream(file);
FileOutputStream fs = new FileOutputStream(newFilePath))
{
int buf;
while ((buf = fi.read()) != -1) {
fs.write(buf);
}
return true;
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询