java之线程安全的单例类和文件拷贝
Posted yunshouhu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java之线程安全的单例类和文件拷贝相关的知识,希望对你有一定的参考价值。
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
//java之线程安全的单例类和文件拷贝
public class MyCopyFile
private static MyCopyFile instance=null;
private MyCopyFile()
//线程安全的单例类
public static MyCopyFile getInstance()
if(instance==null)
synchronized (MyCopyFile.class)
if(instance==null)
instance=new MyCopyFile();
return instance;
public static void main(String[] args)
MyCopyFile.getInstance().copyfile("d:/input.txt", "d:/output.txt");
System.out.println("ok");
private static void copyfile(String input, String output)
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
try
inputStream = new FileInputStream(input);
outputStream = new FileOutputStream(output);
byte buffer[] = new byte[1024];
int len = -1;
while ((len = inputStream.read(buffer)) != -1)
outputStream.write(buffer, 0, len);
outputStream.flush();
outputStream.close();
inputStream.close();
catch (Exception e)
e.printStackTrace();
finally
if (inputStream != null)
try
inputStream.close();
catch (IOException e)
e.printStackTrace();
if (outputStream != null)
try
outputStream.close();
catch (IOException e)
e.printStackTrace();
以上是关于java之线程安全的单例类和文件拷贝的主要内容,如果未能解决你的问题,请参考以下文章