[英]how to backup file in java?
In reality its just making a copy of a text.txt file. 实际上,它只是复制text.txt文件。 I know how to use file chooser to choose the file but that is as far as my knowledge really goes.
我知道如何使用文件选择器来选择文件,但是据我所知。
I can do this: 我可以做这个:
public BasicFile()
{
JFileChooser choose = new JFileChooser(".");
int status = choose.showOpenDialog(null);
try
{
if (status != JFileChooser.APPROVE_OPTION) throw new IOException();
f = choose.getSelectedFile();
if (!f.exists()) throw new FileNotFoundException();
}
catch(FileNotFoundException e)
{
display(1, e.toString(), "File not found ....");
}
catch(IOException e)
{
display(1, e.toString(), "Approve option was not selected");
}
}
Path object is perfect for copying files, 路径对象非常适合复制文件,
Try this code to copy a file, 尝试使用此代码复制文件,
Path source = Paths.get("c:\\blabla.txt");
Path target = Paths.get("c:\\blabla2.txt");
try {
Files.copy(source, target);
} catch (IOException e1) {
e1.printStackTrace();
}
Start by taking a look at Basic I/O , which explains the basics of Input/OutputStreams
and Reader
s and Writer
s, which are used to read/write bytes of data from a source to a destination. 首先看一下Basic I / O ,它解释了
Input/OutputStreams
和Reader
和Writer
的基础,这些基础用于从源到目标读取/写入数据字节。
If you're using Java 7 or over, you should also take a look at Copying a File or Directory which is part of newer Files
and Paths
API, which you can find more information about at File I/O (Featuring NIO.2) 如果您使用的是Java 7或更高版本,则还应查看“ 复制文件或目录” ,它是较新的
Files
和Paths
API的一部分,您可以在文件I / O(功能NIO.2)上找到有关的更多信息。
If you have to backup a whole folder, you can use this code 如果必须备份整个文件夹,则可以使用此代码
public class BackUpFolder {
public void copy(File sourceLocation, File targetLocation) throws IOException {
if (sourceLocation.isDirectory()) {
copyDirectory(sourceLocation, targetLocation);
} else {
copyFile(sourceLocation, targetLocation);
}
}
private void copyDirectory(File source, File target) throws IOException {
if (!target.exists()) {
target.mkdir();
}
for (String f : source.list()) {
copy(new File(source, f), new File(target, f));
}
}
private void copyFile(File source, File target) throws IOException {
try (
InputStream in = new FileInputStream(source);
OutputStream out = new FileOutputStream(target)) {
byte[] buf = new byte[1024];
int length;
while ((length = in.read(buf)) > 0) {
out.write(buf, 0, length);
}
}
}
public static void main(String[] args) {
try {
BackUpFolder backUpFolder = new BackUpFolder();
String location = "./src/edu/abc/locationFiles/daofile"; //File path you are getting from file chooser
String target = "./src"; //target place you want to patse
File locFile = new File(location);
File tarFile = new File(target);
backUpFolder.copyDirectory(locFile, tarFile);
} catch (IOException ex) {
Logger.getLogger(BackUpFolder.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.