1、实现字节流对文件数据的读取
package com.company;
import java.io.*;
import java.util.*;
public class test {
public static void main(String[] args) throws IOException {
FileInputStream ins =new FileInputStream("testfile.txt的具体路径");
int b=0;
while((b=ins.read())!=-1){
System.out.print((char)b);
}
ins.close();
}
}
或者
package com.company;
import java.io.*;
import java.util.*;
public class test {
public static void main(String[] args) throws IOException {
Scanner input =new Scanner(System.in);
InputStream in=null;
try {
String str = input.next().toString(); //文件名
in = new FileInputStream(根目录+str);
int n;
while ((n = in.read()) != -1) { // 读取文件
System.out.println((char) n);
}
}finally { // 如果输入为空,关闭流
if(in !=null)
in.close();
}
}
}
代码中的testfile里面内容是:hello
运行结果:
2、实现字节输出流将数据写入文件
package com.company;
import java.io.*;
import java.util.*;
public class test {
public static void main(String[] args) throws IOException {
Scanner input =new Scanner(System.in);
FileOutputStream ous =new FileOutputStream("testfile2");
String str =input.next().toString();
ous.write(str.getBytes());
ous.close();
}
}
运行后,新建的文件可能不会立即显示,这时候可以通过刷新,显示出新建的文件。
(刷新操作:file->Invalidate Caches / Restart…)
运行结果:输入要存入文件的内容:hellol
3、综合应用:使用字节输出流和输入流,把给定文件里的内容复制到另一个给定文件中。
接收给定的一行字符串(如:/test1/d.txt /test1/e.txt。其中第一个路径为源文件路径,第二个路径为目标文件路径);
使用字节输出流和输入流,把第一个文件里的内容复制到第二个文件中。
import java.io.*;
import java.util.Scanner;
public class FileTest {
public static void main(String[] args) throws IOException {
// 使用字节输出流和输入流,把给定文件里的内容复制到另一个给定文件中
Scanner input =new Scanner(System.in);
String str1 =input.next().toString();
String str2 =input.next().toString();
FileInputStream ins =new FileInputStream(str1);
FileOutputStream ous =new FileOutputStream(str2);
int b=0;
while((b=ins.read())!=-1){
ous.write(b);
}
ins.close();
ous.close();
}
}