java io操作_Java IO 操作
IO操作
Java對數據的操作都是通過流的方式,IO流用來處理設備之間的數據傳輸,文件上傳和文件下載,Java用于操作流的對象都在IO包,NIO(New IO)包中。
創建文件
Java創建文件的方式有三種方式,我們接下來一個一個來介紹。
File.createFile()
java.io.file能夠創建新的文件。創建一個File對象后,可以通過File對象的createNewFile方法創建文件,如果創建成功就返回true,如果創建失敗就返回false。創建成功的文件是一個空文件,創建失敗會拋出IO異常。創建File對象時是需要傳入文件文件目錄和名稱,可以是絕對路徑也可以是相對路徑(相對當前工程的根目錄內,和src同級別).
public class CreateFile {
public static void main(String[] args) {
// 方法一:File.createFile()
File file= new File("./file.txt");
try {
boolean success = file.createNewFile();
if (success) {
System.out.println("Cretea File Success");
} else {
System.out.println("Cretea File Fail");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
FileOutputStream.write(byte[] b)
當創建文件是還想加入一些數據在文件中去,就可以使用FileOutputStream.write這個方法。代碼如下
public class CreateFile {
public static void main(String[] args) {
String data = "Hello world!";
try {
FileOutputStream outputStream = new FileOutputStream("./Hello.txt"); // 創建文件
outputStream.write(data.getBytes()); // 寫入數據
outputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
**NIO Files.write(Path path, byte[] bytes, OpenOption... options) **
NIO就是New IO 的意思,是一個可以替代標準Java IO API的API,提供的和標準IO 不同的工作方式。鏈接, 這里只做簡單的介紹,會用專門的章節進行介紹。
第一個參數Path表示的是一個路徑,可以指向一個路徑或者一個文件夾,也可以是絕對路徑和相對路徑。 例如 Paths.get("/Users/Johnny/Documents/hello.txt") 使用的就是一個絕對路徑,Paths.get("/Users/Johnny", "Documents", "hello.txt") 使用的就是一個相對路徑,相對路徑把所有路徑用目錄分隔符拼接在一起。
第二個參數是寫入的數據。
第三個參數是打開的方式,OpenOption是一個接口,NIO提供了一個StandardOpenOption枚舉類,有READ, WRITE, APPEND, CREATE等。
public class CreateFile {
public static void main(String[] args) {
String data = "Hello world!";
try {
Files.write(Paths.get("./Hello"), data.getBytes(), StandardOpenOption.CREATE);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Paths在nuix系統上文件名沒有大小寫之分。
刪除文件
上面我們學習了如何創建文件,接下來我們學習如何刪除文件和文件夾。
刪除文件和空目錄File.delelte()
如果刪除成功則返回true,文件或者空目錄不存在就會返回false。
File file = new File("./test2");
if (file.delete()) {
System.out.println("刪除成功");
} else {
System.out.println("刪除失敗");
}
如果不是空目錄需要遍歷目錄中的文件,刪除文件,再刪除目錄
如果不是空文件需要把目錄里面的文件先刪除掉,然后再刪除空的目錄
File dir = new File("./test");
if (!dir.isDirectory()) {
System.out.println("不是文件夾");
} else {
File[] files = dir.listFiles();
for (File file: files) {
System.out.println(file.getName());
file.delete();
}
System.out.println("刪除文件夾"+ dir.delete());
}
如果目錄中有目錄,目錄中還有目錄,多層級,就可以用NIO包中的 Files.walkFileTree(Path start, FileVisitor super Path> visitor) 循環遍歷,逐個刪除
第一個參數是路徑。
第二個參數是一個接口,接口定義了四個方法用來指定當你訪問一個節點之前、之中、之后、失敗時應該采取什么行為。
public interface FileVisitor {
FileVisitResult preVisitDirectory(T dir, BasicFileAttributes attrs) // 訪問一個目錄前要干啥
throws IOException;
FileVisitResult postVisitDirectory(T dir, IOException exc) // 訪問一個目錄后要干啥
throws IOException;
FileVisitResult visitFile(T file, BasicFileAttributes attrs) // 正在訪問一個文件時要干啥
throws IOException;
FileVisitResult visitFileFailed(T file, IOException exc) // 訪問一個文件失敗時要干啥
throws IOException;
}
接口返回的是一個FileVisitResult枚舉,分別是
CONTINUE:繼續遍歷
SKIP_SIBLINGS:繼續遍歷,但忽略當前節點的所有兄弟節點直接返回上一層繼續遍歷
SKIP_SUBTREE:繼續遍歷,但是忽略子目錄,但是子文件還是會訪問;
TERMINATE:終止遍歷
遍歷刪除的代碼如下:
public static void main(String[] args) {
Path path = Paths.get("./test");
try {
Files.walkFileTree(path, new SimpleFileVisitor(){
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file); // 刪除文件
return FileVisitResult.CONTINUE; //繼續遍歷
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir); //刪除目錄
return FileVisitResult.CONTINUE; // 繼續遍歷
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
// TODO Auto-generated method stub
return super.preVisitDirectory(dir, attrs);
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
// TODO Auto-generated method stub
return super.visitFileFailed(file, exc);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
分割符
文件分隔符(File.separator):Windows 系統為 \, unix為/;
文件分隔符(File.separatorChar):同上;
文件路徑分割符(File.pathSeparator):Windows 系統為 ;, unix為:;主要用于PATH,CLASSPATH等系統變量。
文件路徑分割符(File.pathSeparatorChar):同上;
為了讓代碼不依賴系統,一般路徑應該使用文件分隔符。
Path path = Paths.get("./test"); // 只適應于Unix系統
Path path = Paths.get(".\test"); // 只適應于windows系統
Path path = Paths.get("."+File.separator+"test"); // 不依賴于系統
重命名文件(移動文件)
可以用File.renameTo去重命名或者移動文件. Unix 系統中如果目標文件存在,則會用源文件覆蓋目標文件。
public static void main(String[] args) {
File sourceFile = new File("."+File.separator+"Source.txt");
File desFile = new File("." + File.separator + "Des.txt");
if (sourceFile.renameTo(desFile)) { // 必須判斷是否成功,因為這個方法不會拋出異常
System.out.println("重命名成功");
} else {
System.out.println("重命名失敗");
}
}
獲取文件大小
IO包中的File.Length
可以用IO包中文件的length方法獲取文件大小,計算的得到的結果單位是byte,需要注意的是確保不是目錄和不存在的文件。
File file = new File("." + File.separator + "test.txt");
System.out.println(file.length());
if (!file.exists() || file.isDirectory()) {
System.out.println("不是文件,計算的長度不正確");
}
NIO包中的FileChannel.size()
Path path = Paths.get("."+File.separator+"file.txt");
FileChannel fileChannel;
try {
fileChannel = FileChannel.open(path, StandardOpenOption.READ); // 打開
long fileSize = fileChannel.size();
System.out.println(fileSize + "bytes");
fileChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
獲取文件擴展名
有時候需要根據不同的文件類型做不同的操作,我們可以通過文件名來獲得文件的擴展名。
private static String getFileName(File file) {
String fileName = file.getName();
if (fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0) { // 如果有(.)且(.)不在第一個字符即不是隱藏文件
return fileName.substring(fileName.lastIndexOf(".") + 1);
}
return null;
}
文件的創建時間、最后更改時間、最后訪問時間
修改時間
File file = new File("." + File.separator + "file.txt");
long createTime = file.lastModified(); // 最后的修改時間戳--距離1970年一月一日的毫秒數,如果文件不存在則返回0
Calendar calendar = Calendar.getInstance(); // 由于Calendar是一個抽象類,不能用new實例化對象,getInstance獲得了一個子類。https://www.cnblogs.com/huangminwen/p/6041168.html
calendar.setTimeInMillis(createTime); // 根據毫秒數得到時間,
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //時間格式化
System.out.println(formatter.format(calendar.getTime())); //2018-09-30 10:57:29
Java7提供了Files.getFileAttributeView(可以獲得最后修改時間,創建時間,文件大小,是否為目錄等等)
private static String createTime(String fileName) {
// 獲取將要操作的文件
Path path = Paths.get(fileName);
// 獲取訪問基本屬性的BasicFileAttributeView
// 兩個參數:1,文件 2,指明一個類,BasicFileAttributeView是指訪問文件的一些基本信息
BasicFileAttributeView attributeView = Files.getFileAttributeView(path, BasicFileAttributeView.class);
BasicFileAttributes attributes;
Calendar calendar = Calendar.getInstance();
try {
attributes = attributeView.readAttributes(); // 獲取信息
calendar.setTimeInMillis(attributes.creationTime().toMillis()); // 創建時間
} catch (IOException e) {
e.printStackTrace();
calendar.setTimeInMillis(0);
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return dateFormat.format(calendar.getTime());
}
attributes.lastAccessTime() 最后獲取時間
attributes.lastModifiedTime() 最后修改時間
attributes.size() 文件大小
getPath()、getAbsolutePath()、getCanonical()
getPath()返回定義時的路徑,(就是你寫什么路徑,他就返回什么路徑)
getAbsolutePath()返回絕對路徑,但不會處理“.”和“..”的情況
getCanonicalPath()返回的是規范化的絕對路徑,相當于將getAbsolutePath()中的“.”和“..”解析成對應的正確的路徑
File file = new File("." + File.separator + "file.txt");
System.out.println(file.getPath()); // ./file.txt
System.out.println(file.getAbsolutePath()); // /Users/Johnny/Documents/./file.txt
try {
System.out.println(file.getCanonicalPath()); // /Users/Johnny/Documents/file.txt
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
設置文件權限PosixFilePermission
java7以上用這種方法,可讀性也非常強。
Set perms = new HashSet();
// 添加用戶權限
perms.add(PosixFilePermission.OWNER_READ);
perms.add(PosixFilePermission.OWNER_WRITE);
perms.add(PosixFilePermission.OTHERS_EXECUTE);
//添加群權限
perms.add(PosixFilePermission.GROUP_READ);
perms.add(PosixFilePermission.GROUP_WRITE);
perms.add(PosixFilePermission.GROUP_EXECUTE);
// 添加其他人員的權限
perms.add(PosixFilePermission.OTHERS_READ);
perms.add(PosixFilePermission.OTHERS_WRITE);
perms.add(PosixFilePermission.OTHERS_EXECUTE);
try {
Files.setPosixFilePermissions(Paths.get("." + File.separator + "file.txt"), perms);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
復制文件
Stream的方式:創建一個源文件和一個目標文件,從源文件建立一個輸入流,用輸出流寫入目標文件
private static void copyFileUsingStream(File source, File dest) {
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
fileInputStream = new FileInputStream(source);
fileOutputStream = new FileOutputStream(dest);
//定義一個字節數組,相當于緩存
byte[] buffer = new byte[1024];
int length;
//循環讀取
while ((length = fileInputStream.read(buffer)) != -1) { //把fileInputStream里的東西讀到bytes數組里去
fileOutputStream.write(buffer, 0, length); // 把字節寫入文件中
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//一定要關閉文件流, 并且關閉文件流必須放在finally里面
try {
fileInputStream.close();
fileOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
NIO 的 FileChannel 的 transform()
private static void copyFileUsingFileChannel(File source, File dest) {
FileChannel sourceChannel = null;
FileChannel desChannel = null;
try {
sourceChannel = new FileInputStream(source).getChannel();
desChannel = new FileOutputStream(dest).getChannel();
desChannel.transferFrom(sourceChannel, 0, source.length());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
sourceChannel.close();
desChannel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Files的copy方法 -- Java7 以上可以用,它使用FileSystemProvider來復制文件
try {
Files.copy(source.toPath(), dest.toPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
讀取文本內容
java.nio.file.Files
Files能夠把內容讀取出來變成一個byte數組,也可以把所有的行變成變成字符串數組。這些方法適合于把不是太大的文件讀入內存中。
Path path = Paths.get("." + File.separator + "source.txt");
try {
//Java7 讀取所有的內容,默認以UTF-8編碼讀入文件,故文件的編碼如果不是UTF-8,那么中文內容會出現亂字符
byte[] bytes = Files.readAllBytes(path);
System.out.println(new String(bytes));
// Java8
List lists = Files.readAllLines(path);
System.out.println(lists); // [string1, string2, ...]
} catch (IOException e) {
e.printStackTrace();
}
java.io.FileReader
可以通過FileReader獲得BufferedReader,然后一行一行的讀取文件。
File file = new File("." + File.separator + "source.txt");
try {
FileReader reader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
java.io.BufferedReader
BufferedReader適合于大文件,且是線程安全的特點,默認的緩存大小是8KB。
File file = new File("." + File.separator + "source.txt");
BufferedReader bufferedReader = null;
try {
FileInputStream inputStream = new FileInputStream(file);
InputStreamReader reader = new InputStreamReader(inputStream);
bufferedReader = new BufferedReader(reader);
String line;
while((line = bufferedReader.readLine()) != null){
//process the line
System.out.println(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
bufferedReader.close(); // 關閉流
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Files.BufferedReader
try {
BufferedReader bufferedReader = Files.newBufferedReader(Paths.get("." + File.separator + "source.txt"));
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Scanner
Path path = Paths.get("." + File.separator + "source.txt");
try {
Scanner scanner = new Scanner(path);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
打開文件(DeskTop)
java.awt.Desktop這個類能打開文件,但是調用之前需要判斷是否支持java.awt.Desktop.
File sourceFile = new File("."+File.separator+"source.txt");
if (!Desktop.isDesktopSupported()) {
System.out.println("Desktop is not supported");
return;
}
Desktop desktop = Desktop.getDesktop();
try {
desktop.open(sourceFile); // 打開文件
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
讀取文本文件成為字符串
BufferedReader
String pathname = "." + File.separator + "source.txt";
try {
FileReader fileReader = new FileReader(new File(pathname));
BufferedReader bufferedReader = new BufferedReader(fileReader); // bufferreader
StringBuilder stringBuilder = new StringBuilder();
String line = null;
String ls = System.getProperty("line.separator"); // 換行符
while ((line = bufferedReader.readLine()) != null) { // 讀取的每行的數據
stringBuilder.append(line); // 寫入數據
stringBuilder.append(ls); // 寫入換行符
}
stringBuilder.deleteCharAt(stringBuilder.length()-1); // 刪除最后一個換行符
bufferedReader.close(); // 關流
String content = stringBuilder.toString(); // 字符
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileInputStream
String pathname = "." + File.separator + "source.txt";
try {
FileInputStream inputStream = new FileInputStream(new File(pathname));
byte[] bytes = new byte[10];
StringBuffer stringBuffer = new StringBuffer();
while (inputStream.read(bytes) != -1) {
stringBuffer.append(new String(bytes));
bytes = new byte[10];
}
inputStream.close();
String content = stringBuffer.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Files
String content = new String(Files.readAllBytes(Paths.get(fileName)));
寫文件(會覆蓋原有內容)
FileWriter
File file = new File("." + File.separator + "des.txt");
String data = "Writed Data using FileWriter";
FileWriter fw = null;
try {
fw = new FileWriter(file);
fw.write(data);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
BufferedWriter
File file = new File("." + File.separator + "des.txt");
String data = "Write using bufferwriter";
FileWriter fWriter = null;
BufferedWriter bWriter = null;
try {
fWriter = new FileWriter(file);
bWriter = new BufferedWriter(fWriter);
bWriter.write(data);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
bWriter.close();
fWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
FileOutputStream
File file = new File("." + File.separator + "des.txt");
String data = "Write using outputstream";
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file);
outputStream.write(data.getBytes(), 0, data.length());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
outputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Files
String data = "Write using Files";
try {
Files.write(Paths.get("." + File.separator + "des.txt"), data.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
給文件增加內容
FileWriter
File file = new File("." + File.separator + "append.txt");
FileWriter fr = null;
try {
fr = new FileWriter(file, true); // 第二個參數就是是否是增加
fr.write(System.getProperty("line.separator") + "Append String using file writer");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
BufferedWriter
File file = new File("." + File.separator + "append.txt");
String data = System.getProperty("line.separator") + "Append using bufferwriter";
FileWriter fWriter = null;
BufferedWriter bWriter = null;
try {
fWriter = new FileWriter(file, true);
bWriter = new BufferedWriter(fWriter);
bWriter.write(data);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
bWriter.close();
fWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
FileOutputStream
File file = new File("." + File.separator + "append.txt");
String data = System.getProperty("line.separator") + "Append using outputstream";
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file, true); // 第二個參數就是是否是增加
outputStream.write(data.getBytes(), 0, data.length());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
outputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
PrintWriter
File file = new File("." + File.separator + "append.txt");
FileWriter fr = new FileWriter(file, true);
BufferedWriter br = new BufferedWriter(fr);
PrintWriter pr = new PrintWriter(br);
pr.println(System.getProperty("line.separator") + "Append using printwriter");
pr.close();
br.close();
fr.close();
在文件的指定位置讀寫(RandomAccessFile)
RandomAccessFile 是隨機訪問文件(包括讀/寫)的類,我們可以從指定的位置讀取/寫入文件數據。
讀取數據
RandomAccessFile file = null;
try {
file = new RandomAccessFile("source.txt", "r"); // 第一個參數是文件路徑,第二個參數r表示只讀
file.seek(4); //游標移動四個位置
byte[] bytes = new byte[2]; // 兩個字符的緩存
file.read(bytes); // 讀入兩個字符到緩存中
System.out.println(new String(bytes)); // 打印讀取出來的兩個字符
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
在某處寫入數據
RandomAccessFile file = null;
try {
file = new RandomAccessFile("source.txt", "rw"); // 第一個參數是文件路徑,第二個參數rw表示讀寫
file.seek(4); //游標移動四個位置
file.write("Insert data".getBytes()); // 在第五個字符位置插入數據
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
在文件末尾寫入數據
file.seek(file.length()); // 把游標移動到文件的末尾,其他操作和插入操作一樣
網絡下載文件
InputStream
BufferedInputStream bis = null;
FileOutputStream fos = null;
try {
//url代表一個絕對地址,URL對象直接指向這個資源
URL url = new URL("http://pic6.nipic.com/20100417/1304280_085257009323_2.jpg");
// url.openStream()返回為InputStream
bis = new BufferedInputStream(url.openStream());
// 存入本地文件
fos = new FileOutputStream("." + File.separator + "meinv.jpg");
byte[] bytes = new byte[1024];
int count = 0;
while ((count = bis.read(bytes)) != -1) {
fos.write(bytes, 0, count);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
NIO Channel
ReadableByteChannel rbc = null;
FileOutputStream fos = null;
try {
//url代表一個絕對地址,URL對象直接指向這個資源
URL url = new URL("http://pic6.nipic.com/20100417/1304280_085257009323_2.jpg");
rbc = Channels.newChannel(url.openStream());
fos = new FileOutputStream("." + File.separator + "meinv.jpg");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
rbc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
壓縮和解壓縮文件
壓縮文件
FileInputStream fis = null;
FileOutputStream fos = null;
GZIPOutputStream gos = null;
try {
fis = new FileInputStream("./meinv.jpg"); // 輸入流
fos = new FileOutputStream("./Meinv.gz"); // 輸出流
gos = new GZIPOutputStream(fos); // 壓縮輸出流
byte[] buffer = new byte[1024];
int count = 0;
while ((count = fis.read(buffer)) != -1) {
gos.write(buffer, 0, count);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
gos.close();
fos.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
解壓縮文件
FileInputStream fis = null;
GZIPInputStream gis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("./Meinv.gz");
gis = new GZIPInputStream(fis);
fos = new FileOutputStream("./new.jpg");
byte[] buffer = new byte[1024];
int len;
while ((len = gis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
gis.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
創建臨時文件
createTempFile(String prefix, String suffix, File directory) 可以用來創建臨時文件,創建出來的文件名稱是prefix+random_long_no+suffix,如果suffix給null,則為.tmp, 如果directory不給,則為系統默認的臨時文件夾。
File tmpFile = File.createTempFile("data", null);
總結
以上是生活随笔為你收集整理的java io操作_Java IO 操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java和equals区别_JAVA中=
- 下一篇: python合并csv文件_PYTHON