Java io
创建文件的三种方式:
// File file = new File("D:\\", "aaa.txt");
// File file = new File("D:\\bbb.txt");
// File file = new File(new File("D:\\"), "ccc.txt");
public class Main {
public static void main(String[] args) throws IOException {
File file = new File(new File("D:\\"), "ccc.txt");
try (InputStream fileInputStream = new FileInputStream(file)) {
int read;
while((read=fileInputStream.read())!=-1){
System.out.print((char)read);
}
}catch (IOException e){
System.out.println(e.getMessage());
}
try (InputStream fileInputStream = new FileInputStream(file)) {
byte[] buff=new byte[8];
int len;
while((len=fileInputStream.read(buff))!=-1){
System.out.print(new String(buff,0,len));
}
}catch (IOException e){
System.out.println(e.getMessage());
}
}
}
String sourceFile = "D:\\ccc.txt";
String targetFile = "D:\\ddd.txt";
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
fileInputStream = new FileInputStream(sourceFile);
fileOutputStream = new FileOutputStream(targetFile);
byte[] buff = new byte[1024];
int readLine = 0;
while ((readLine = fileInputStream.read(buff)) != -1) {
fileOutputStream.write(buff, 0, readLine);
}
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
if (fileInputStream != null) {
fileInputStream.close();
}
if (fileOutputStream != null) {
fileOutputStream.close();
}
}
try (FileReader reader = new FileReader("D:\\ccc.txt")) {
char[] context=new char[1024];
int len=0;
while((len= reader.read(context))!=-1){
System.out.println(new String(context,0,len));
}
} catch (IOException e) {
throw new RuntimeException(e);
}