public class Main {
public static void main(String[] args) {
String pathName = "D:/i.txt";
String outName = "D:\\o.txt";
byte[] bytes = new byte[27];
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(pathName);
int read;
while ((read = fis.read(bytes))!= -1 ){
for (int i = 0;i < read;i++){
System.out.println(bytes[i]);
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
try {
fis.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
这个是读入的代码,现在要将读入的内容写出
String outName = "D:\\o.txt";
FileOutputStream fos = null;
String outName = "D:\\o.txt";这个是确定要写出的位置FileOutputStream fos = null;这个是搭建管道,
public class Main {
public static void main(String[] args) {
String pathName = "D:/i.txt";
String outName = "D:\\o.txt";
byte[] bytes = new byte[27];
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(pathName);
int read;
while ((read = fis.read(bytes))!= -1 ){
for (int i = 0;i < read;i++){
System.out.print(bytes[i]);
System.out.println(read);
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
try {
fis.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
这样准备就做好了,然后要打开流将东西写出,想写出就需要用到write方法
public class Main {
public static void main(String[] args) {
String pathName = "D:/i.txt";
String outName = "D:\\o.txt";
byte[] bytes = new byte[27];
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(pathName);
fos = new FileOutputStream(outName);
int read;
while ((read = fis.read(bytes))!= -1 ){
for (int i = 0;i < read;i++){
System.out.println(bytes[i]);
}
fos.write(bytes,0,bytes.length);
}
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
try {
fos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
fis.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
但是这样写出来后 o.txt文件中会多出来许多空格,这是因为每次写入的都是bytes.length的长度,当i.txt文件中没有填满bytes就会出现空格我们可以将write方法中的
fos.write(bytes,0,bytes.length);
换成
fos.write(bytes,0,read);
就可以了,这和read方法的返回值有关。
这样就将D:/i.txt文件中的内容写入D:\\o.txt文件中了,这个不仅可以写txt的文件 还可以写照片和视频,只要将这个代码写成一个方法,每次调用就会方便很多
这样就可以了
public class Main {
public static void main(String[] args) {
String pathName = "D:/i.txt";
String outName = "D:/0.txt";
copy(pathName,outName,5);
}
public static void copy(String pathName,String outName,int index){
byte[] bytes = new byte[index];
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(pathName);
fos = new FileOutputStream(outName);
int read;
while ((read = fis.read(bytes))!= -1 ){
fos.write(bytes,0,bytes.length);
fos.flush();
}
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
try {
fos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
fis.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
这样就可以了,想要用的时候就直接调用方法