import java.io.BufferedReader
import java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.FileWriter
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
/**
* java读写文件,复制文件
* 读取d:/1.txt文件内容,写入f:/text.txt文件中.
* @author young
*
*/
public class FileWriterTest {
// 读写文件
public static void rwFile(){
FileWriter fw = null
BufferedReader br = null
try {
fw = new FileWriter("f:\\text.txt", true)
br = new BufferedReader(new InputStreamReader(
new FileInputStream("d:\\1.txt"), "UTF-8"))
String line = null
while ((line = br.readLine()) != null) {
System.out.println("文件内容旅启: " + line)
fw.write(line)
fw.flush()
}
br.close()
} catch (FileNotFoundException e) {
e.printStackTrace()
} catch (IOException e) {
e.printStackTrace()
} finally {
if (fw != null) {
try {
fw.close()
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace()
}
}
}
}
public static void main(String[] args) {
rwFile()
}
}
首先在D盘新建文件1.txt,输入任意内容。然后执行java代码即可。拆核如氏枝
你可以个java inputStrem流和outputStream流来实现这个功能。import java.io.*
public class FileStreamDemo {
public static void main(String[] args) {
try {
// 来源文件
FileInputStream in = new FileInputStream("D:/b.txt")
// 目的文件
FileOutputStream out = new FileOutputStream("C:/a.txt")
byte[] bytearray = new byte[1024]
do {
in.read(bytearray, 0, 1024)
out.write(bytearray)
} while (in.available() >0)
in.close()
out.close()
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace()
} catch (IOException e) {
e.printStackTrace()
}
}
}
package tv.bilibiliimport java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.io.FileOutputStream
public class IoPlay {
public static void main(String[] args) throws IOException{
File f = new File("E:\\新建文本文档.txt")
File f1 = new File("D:\\")
IoPlay io = new IoPlay()
io.copy(f,f1)
}
public void copy(File f,File f1) throws IOException{//复制文件的方法!
if(!f1.exists()){
f1.mkdir()
}
if(!f1.exists()){//路径判断,是路径还是单个的文件
File[] cf = f.listFiles()
for(File fn : cf){
if(fn.isFile()){
FileInputStream fis = new FileInputStream(fn)
FileOutputStream fos = new FileOutputStream(f1 + "\\" +fn.getName())
byte[] b = new byte[1024]
int i = fis.read(b)
while(i != -1){
fos.write(b, 0, i)
i = fis.read(b)
}
fis.close()
fos.close()
}else{
File fb = new File(f1 + "\\" + fn.getName())
fb.mkdir()
if(fn.listFiles() != null){//如塌培果有子目录递归复制子目录!
copy(fn,fb)
}
}
}
}else{
FileInputStream fis = new FileInputStream(f)
FileOutputStream fos = new FileOutputStream(f1 + "\银衫段\" +f.getName())
byte[] b = new byte[1024]
int i = fis.read(b)
while(i != -1){
fos.write(b, 0, i)
i = fis.read(b)
}
fis.close()
fos.close()
}
}
}
以上是我自己写的,讲一个文件复制到例外一个锋誉地方,无论是文件,还是文件夹都可以
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)