Java【IO系列】基礎篇—16. PrintWriter和RandomAccessFile詳解

2021-02-14 人人有架設

目錄
1. PrintWriter 介紹
2. PrintWriter 源碼
3. 示例代碼

1. PrintWriter 介紹

PrintWriter 是字符類型的列印輸出流,它繼承於Writer。

PrintStream 用於向文本輸出流列印對象的格式化表示形式。它實現在 PrintStream 中的所有 print 方法。它不包含用於寫入原始字節的方法,對於這些字節,程序應該使用未編碼的字節流進行寫入。

PrintWriter 函數列表

PrintWriter(OutputStream out)
PrintWriter(OutputStream out, boolean autoFlush)
PrintWriter(Writer wr)
PrintWriter(Writer wr, boolean autoFlush)
PrintWriter(File file)
PrintWriter(File file, String csn)
PrintWriter(String fileName)
PrintWriter(String fileName, String csn)

PrintWriter append(char c)
PrintWriter append(CharSequence csq, int start, int end)
PrintWriter append(CharSequence csq)
boolean checkError()
void close()
void flush()
PrintWriter format(Locale l, String format, Object... args)
PrintWriter format(String format, Object... args)
void print(float fnum)
void print(double dnum)
void print(String str)
void print(Object obj)
void print(char ch)
void print(char[] charArray)
void print(long lnum)
void print(int inum)
void print(boolean bool)
PrintWriter printf(Locale l, String format, Object... args)
PrintWriter printf(String format, Object... args)
void println()
void println(float f)
void println(int i)
void println(long l)
void println(Object obj)
void println(char[] chars)
void println(String str)
void println(char c)
void println(double d)
void println(boolean b)
void write(char[] buf, int offset, int count)
void write(int oneChar)
void write(char[] buf)
void write(String str, int offset, int count)
void write(String str)

2. PrintWriter 源碼

package java.io;

import java.util.Objects;
import java.util.Formatter;
import java.util.Locale;
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.UnsupportedCharsetException;

public class PrintWriter extends Writer {

protected Writer out;

// 自動flush
// 所謂「自動flush」,就是每次執行print(), println(), write()函數,都會調用flush()函數;
// 而「不自動flush」,則需要我們手動調用flush()接口。
private final boolean autoFlush;
// PrintWriter是否右產生異常。當PrintWriter有異常產生時,會被本身捕獲,並設置trouble為true
private boolean trouble = false;
// 用于格式化的對象
private Formatter formatter;
private PrintStream psOut = null;

// 行分割符
private final String lineSeparator;

// 獲取csn(字符集名字)對應的Chaset
private static Charset toCharset(String csn)
throws UnsupportedEncodingException
{
Objects.requireNonNull(csn, "charsetName");
try {
return Charset.forName(csn);
} catch (IllegalCharsetNameException|UnsupportedCharsetException unused) {
// UnsupportedEncodingException should be thrown
throw new UnsupportedEncodingException(csn);
}
}

// 將「Writer對象out」作為PrintWriter的輸出流,默認不會自動flush,並且採用默認字符集。
public PrintWriter (Writer out) {
this(out, false);
}

// 將「Writer對象out」作為PrintWriter的輸出流,autoFlush的flush模式,並且採用默認字符集。
public PrintWriter(Writer out, boolean autoFlush) {
super(out);
this.out = out;
this.autoFlush = autoFlush;
lineSeparator = java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction("line.separator"));
}

// 將「輸出流對象out」作為PrintWriter的輸出流,不自動flush,並且採用默認字符集。
public PrintWriter(OutputStream out) {
this(out, false);
}

// 將「輸出流對象out」作為PrintWriter的輸出流,autoFlush的flush模式,並且採用默認字符集。
public PrintWriter(OutputStream out, boolean autoFlush) {
// new OutputStreamWriter(out):將「字節類型的輸出流」轉換為「字符類型的輸出流」
// new BufferedWriter(...): 為輸出流提供緩衝功能。
this(new BufferedWriter(new OutputStreamWriter(out)), autoFlush);

// save print stream for error propagation
if (out instanceof java.io.PrintStream) {
psOut = (PrintStream) out;
}
}

// 創建fileName對應的OutputStreamWriter,進而創建BufferedWriter對象;然後將該BufferedWriter作為PrintWriter的輸出流,不自動flush,採用默認字符集。
public PrintWriter(String fileName) throws FileNotFoundException {
this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName))),
false);
}

// 創建fileName對應的OutputStreamWriter,進而創建BufferedWriter對象;然後將該BufferedWriter作為PrintWriter的輸出流,不自動flush,採用字符集charset。
private PrintWriter(Charset charset, File file)
throws FileNotFoundException
{
this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset)),
false);
}

// 創建fileName對應的OutputStreamWriter,進而創建BufferedWriter對象;然後將該BufferedWriter作為PrintWriter的輸出流,不自動flush,採用csn字符集。
public PrintWriter(String fileName, String csn)
throws FileNotFoundException, UnsupportedEncodingException
{
this(toCharset(csn), new File(fileName));
}

// 創建file對應的OutputStreamWriter,進而創建BufferedWriter對象;然後將該BufferedWriter作為PrintWriter的輸出流,不自動flush,採用默認字符集。
public PrintWriter(File file) throws FileNotFoundException {
this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))),
false);
}

// 創建file對應的OutputStreamWriter,進而創建BufferedWriter對象;然後將該BufferedWriter作為PrintWriter的輸出流,不自動flush,採用csn字符集。
public PrintWriter(File file, String csn)
throws FileNotFoundException, UnsupportedEncodingException
{
this(toCharset(csn), file);
}

private void ensureOpen() throws IOException {
if (out == null)
throw new IOException("Stream closed");
}

// flush「PrintWriter輸出流中的數據」。
public void flush() {
try {
synchronized (lock) {
ensureOpen();
out.flush();
}
}
catch (IOException x) {
trouble = true;
}
}

public void close() {
try {
synchronized (lock) {
if (out == null)
return;
out.close();
out = null;
}
}
catch (IOException x) {
trouble = true;
}
}

// flush「PrintWriter輸出流緩衝中的數據」,並檢查錯誤
public boolean checkError() {
if (out != null) {
flush();
}
if (out instanceof java.io.PrintWriter) {
PrintWriter pw = (PrintWriter) out;
return pw.checkError();
} else if (psOut != null) {
return psOut.checkError();
}
return trouble;
}

protected void setError() {
trouble = true;
}

protected void clearError() {
trouble = false;
}

// 將字符c寫入到「PrintWriter輸出流」中。c雖然是int類型,但實際只會寫入一個字符
public void write(int c) {
try {
synchronized (lock) {
ensureOpen();
out.write(c);
}
}
catch (InterruptedIOException x) {
Thread.currentThread().interrupt();
}
catch (IOException x) {
trouble = true;
}
}

// 將「buf中從off開始的len個字符」寫入到「PrintWriter輸出流」中。
public void write(char buf[], int off, int len) {
try {
synchronized (lock) {
ensureOpen();
out.write(buf, off, len);
}
}
catch (InterruptedIOException x) {
Thread.currentThread().interrupt();
}
catch (IOException x) {
trouble = true;
}
}

// 將「buf中的全部數據」寫入到「PrintWriter輸出流」中。
public void write(char buf[]) {
write(buf, 0, buf.length);
}

// 將「字符串s中從off開始的len個字符」寫入到「PrintWriter輸出流」中。
public void write(String s, int off, int len) {
try {
synchronized (lock) {
ensureOpen();
out.write(s, off, len);
}
}
catch (InterruptedIOException x) {
Thread.currentThread().interrupt();
}
catch (IOException x) {
trouble = true;
}
}

// 將「字符串s」寫入到「PrintWriter輸出流」中。
public void write(String s) {
write(s, 0, s.length());
}

// 將「換行符」寫入到「PrintWriter輸出流」中。
private void newLine() {
try {
synchronized (lock) {
ensureOpen();
out.write(lineSeparator);
if (autoFlush)
out.flush();
}
}
catch (InterruptedIOException x) {
Thread.currentThread().interrupt();
}
catch (IOException x) {
trouble = true;
}
}

// 將「boolean數據對應的字符串」寫入到「PrintWriter輸出流」中,print實際調用的是write函數
public void print(boolean b) {
write(b ? "true" : "false");
}

// 將「字符c對應的字符串」寫入到「PrintWriter輸出流」中,print實際調用的是write函數
public void print(char c) {
write(c);
}

// 將「int數據i對應的字符串」寫入到「PrintWriter輸出流」中,print實際調用的是write函數
public void print(int i) {
write(String.valueOf(i));
}

// 將「long型數據l對應的字符串」寫入到「PrintWriter輸出流」中,print實際調用的是write函數
public void print(long l) {
write(String.valueOf(l));
}

// 將「float數據f對應的字符串」寫入到「PrintWriter輸出流」中,print實際調用的是write函數
public void print(float f) {
write(String.valueOf(f));
}

// 將「double數據d對應的字符串」寫入到「PrintWriter輸出流」中,print實際調用的是write函數
public void print(double d) {
write(String.valueOf(d));
}

// 將「字符數組s」寫入到「PrintWriter輸出流」中,print實際調用的是write函數
public void print(char s[]) {
write(s);
}

// 將「字符串數據s」寫入到「PrintWriter輸出流」中,print實際調用的是write函數
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}

// 將「對象obj對應的字符串」寫入到「PrintWriter輸出流」中,print實際調用的是write函數
public void print(Object obj) {
write(String.valueOf(obj));
}

// 將「換行符」寫入到「PrintWriter輸出流」中,println實際調用的是write函數
public void println() {
newLine();
}

// 將「boolean數據對應的字符串+換行符」寫入到「PrintWriter輸出流」中,println實際調用的是write函數
public void println(boolean x) {
synchronized (lock) {
print(x);
println();
}
}

// 將「字符x對應的字符串+換行符」寫入到「PrintWriter輸出流」中,println實際調用的是write函數
public void println(char x) {
synchronized (lock) {
print(x);
println();
}
}

// 將「int數據對應的字符串+換行符」寫入到「PrintWriter輸出流」中,println實際調用的是write函數
public void println(int x) {
synchronized (lock) {
print(x);
println();
}
}

// 將「long數據對應的字符串+換行符」寫入到「PrintWriter輸出流」中,println實際調用的是write函數
public void println(long x) {
synchronized (lock) {
print(x);
println();
}
}

// 將「float數據對應的字符串+換行符」寫入到「PrintWriter輸出流」中,println實際調用的是write函數
public void println(float x) {
synchronized (lock) {
print(x);
println();
}
}

// 將「double數據對應的字符串+換行符」寫入到「PrintWriter輸出流」中,println實際調用的是write函數
public void println(double x) {
synchronized (lock) {
print(x);
println();
}
}

// 將「字符數組x+換行符」寫入到「PrintWriter輸出流」中,println實際調用的是write函數
public void println(char x[]) {
synchronized (lock) {
print(x);
println();
}
}

// 將「字符串x+換行符」寫入到「PrintWriter輸出流」中,println實際調用的是write函數
public void println(String x) {
synchronized (lock) {
print(x);
println();
}
}

// 將「對象o對應的字符串+換行符」寫入到「PrintWriter輸出流」中,println實際調用的是write函數
public void println(Object x) {
String s = String.valueOf(x);
synchronized (lock) {
print(s);
println();
}
}

// 將「數據args」根據「默認Locale值(區域屬性)」按照format格式化,並寫入到「PrintWriter輸出流」中
public PrintWriter printf(String format, Object ... args) {
return format(format, args);
}

// 將「數據args」根據「Locale值(區域屬性)」按照format格式化,並寫入到「PrintWriter輸出流」中
public PrintWriter printf(Locale l, String format, Object ... args) {
return format(l, format, args);
}

// 根據「默認的Locale值(區域屬性)」來格式化數據
public PrintWriter format(String format, Object ... args) {
try {
synchronized (lock) {
ensureOpen();
if ((formatter == null)
|| (formatter.locale() != Locale.getDefault()))
formatter = new Formatter(this);
formatter.format(Locale.getDefault(), format, args);
if (autoFlush)
out.flush();
}
} catch (InterruptedIOException x) {
Thread.currentThread().interrupt();
} catch (IOException x) {
trouble = true;
}
return this;
}

// 根據「Locale值(區域屬性)」來格式化數據
public PrintWriter format(Locale l, String format, Object ... args) {
try {
synchronized (lock) {
ensureOpen();
if ((formatter == null) || (formatter.locale() != l))
formatter = new Formatter(this, l);
formatter.format(l, format, args);
if (autoFlush)
out.flush();
}
} catch (InterruptedIOException x) {
Thread.currentThread().interrupt();
} catch (IOException x) {
trouble = true;
}
return this;
}

// 將「字符序列的全部字符」追加到「PrintWriter輸出流中」
public PrintWriter append(CharSequence csq) {
if (csq == null)
write("null");
else
write(csq.toString());
return this;
}

// 將「字符序列從start(包括)到end(不包括)的全部字符」追加到「PrintWriter輸出流中」
public PrintWriter append(CharSequence csq, int start, int end) {
CharSequence cs = (csq == null ? "null" : csq);
write(cs.subSequence(start, end).toString());
return this;
}

// 將「字符c」追加到「PrintWriter輸出流中」
public PrintWriter append(char c) {
write(c);
return this;
}
}

3. 示例代碼

關於PrintWriter中API的詳細用法,參考示例代碼(PrintWriterTest.java):

import java.io.PrintWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
* PrintWriter 的示例程序
*
*/
public class PrintWriterTest {

public static void main(String[] args) {

// 下面3個函數的作用都是一樣:都是將字母「abcde」寫入到文件「file.txt」中。
// 任選一個執行即可!
testPrintWriterConstrutor1() ;
//testPrintWriterConstrutor2() ;
//testPrintWriterConstrutor3() ;

// 測試write(), print(), println(), printf()等接口。
testPrintWriterAPIS() ;
}

/**
* PrintWriter(OutputStream out) 的測試函數
*
* 函數的作用,就是將字母「abcde」寫入到文件「file.txt」中
*/
private static void testPrintWriterConstrutor1() {
final char[] arr={'a', 'b', 'c', 'd', 'e' };
try {
// 創建文件「file.txt」的File對象
File file = new File("file.txt");
// 創建文件對應FileOutputStream
PrintWriter out = new PrintWriter(
new FileOutputStream(file));
// 將「字節數組arr」全部寫入到輸出流中
out.write(arr);
// 關閉輸出流
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* PrintWriter(File file) 的測試函數
*
* 函數的作用,就是將字母「abcde」寫入到文件「file.txt」中
*/
private static void testPrintWriterConstrutor2() {
final char[] arr={'a', 'b', 'c', 'd', 'e' };
try {
File file = new File("file.txt");
PrintWriter out = new PrintWriter(file);
out.write(arr);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* PrintWriter(String fileName) 的測試函數
*
* 函數的作用,就是將字母「abcde」寫入到文件「file.txt」中
*/
private static void testPrintWriterConstrutor3() {
final char[] arr={'a', 'b', 'c', 'd', 'e' };
try {
PrintWriter out = new PrintWriter("file.txt");
out.write(arr);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* 測試write(), print(), println(), printf()等接口。
*/
private static void testPrintWriterAPIS() {
final char[] arr={'a', 'b', 'c', 'd', 'e' };
try {
// 創建文件對應FileOutputStream
PrintWriter out = new PrintWriter("other.txt");

// 將字符串「hello PrintWriter」+回車符,寫入到輸出流中
out.println("hello PrintWriter");
// 將0x41寫入到輸出流中
// 0x41對應ASCII碼的字母'A',也就是寫入字符'A'
out.write(0x41);
// 將字符串"65"寫入到輸出流中。
// out.print(0x41); 等價於 out.write(String.valueOf(0x41));
out.print(0x41);
// 將字符'B'追加到輸出流中
out.append('B').append("CDEF");

// 將"CDE is 5" + 回車 寫入到輸出流中
String str = "GHI";
int num = 5;
out.printf("%s is %d\n", str, num);

out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

運行上面的代碼,會在源碼所在目錄生成兩個文件「file.txt」和「other.txt」。

file.txt的內容如下:

abcde

other.txt的內容如下:

hello PrintWriter
A65BCDEFGHI is 5

RandomAccessFile詳解1. RandomAccessFile

RandomAccessFile 是隨機訪問文件(包括讀/寫)的類。它支持對文件隨機訪問的讀取和寫入,即我們可以從指定的位置讀取/寫入文件數據。

需要注意的是,RandomAccessFile 雖然屬於java.io包,但它不是InputStream或者OutputStream的子類;它也不同於FileInputStream和FileOutputStream。FileInputStream 只能對文件進行讀操作,而FileOutputStream 只能對文件進行寫操作;但是,RandomAccessFile 同時支持文件的讀和寫,並且它支持隨機訪問。

RandomAccessFile 函數列表

RandomAccessFile(File file, String mode)
RandomAccessFile(String fileName, String mode)

void close()
synchronized final FileChannel getChannel()
final FileDescriptor getFD()
long getFilePointer()
long length()
int read(byte[] buffer, int byteOffset, int byteCount)
int read(byte[] buffer)
int read()
final boolean readBoolean()
final byte readByte()
final char readChar()
final double readDouble()
final float readFloat()
final void readFully(byte[] dst)
final void readFully(byte[] dst, int offset, int byteCount)
final int readInt()
final String readLine()
final long readLong()
final short readShort()
final String readUTF()
final int readUnsignedByte()
final int readUnsignedShort()
void seek(long offset)
void setLength(long newLength)
int skipBytes(int count)
void write(int oneByte)
void write(byte[] buffer, int byteOffset, int byteCount)
void write(byte[] buffer)
final void writeBoolean(boolean val)
final void writeByte(int val)
final void writeBytes(String str)
final void writeChar(int val)
final void writeChars(String str)
final void writeDouble(double val)
final void writeFloat(float val)
final void writeInt(int val)
final void writeLong(long val)
final void writeShort(int val)
final void writeUTF(String str)

2. RandomAccessFile 模式說明

RandomAccessFile共有4種模式:"r", "rw", "rws"和"rwd"。

"r" 以只讀方式打開。調用結果對象的任何 write 方法都將導致拋出 IOException。
"rw" 打開以便讀取和寫入。
"rws" 打開以便讀取和寫入。相對於 "rw","rws" 還要求對「文件的內容」或「元數據」的每個更新都同步寫入到基礎存儲設備。
"rwd" 打開以便讀取和寫入,相對於 "rw","rwd" 還要求對「文件的內容」的每個更新都同步寫入到基礎存儲設備。

說明:

(01) 什麼是「元數據」,即metadata?

英文解釋如下:

The definition of metadata is "data about other data." With a file system, the data is contained in its files and directories, and the metadata tracks information about each of these objects: Is it a regular file, a directory, or a link? What is its size, creation date, last modified date, file owner, group owner, and access permissions?

大致意思是:
metadata是「關於數據的數據」。在文件系統中,數據被包含在文件和文件夾中;metadata信息包括:「數據是一個文件,一個目錄還是一個連結」,「數據的創建時間(簡稱ctime)」,「最後一次修改時間(簡稱mtime)」,「數據擁有者」,「數據擁有群組」,「訪問權限」等等。

(02) "rw", "rws", "rwd" 的區別。

當操作的文件是存儲在本地的基礎存儲設備上時(如硬碟, NandFlash等),"rws" 或 "rwd", "rw" 才有區別。
當模式是 "rws" 並且 操作的是基礎存儲設備上的文件;那麼,每次「更改文件內容[如write()寫入數據]」 或 「修改文件元數據(如文件的mtime)」時,都會將這些改變同步到基礎存儲設備上。
當模式是 "rwd" 並且 操作的是基礎存儲設備上的文件;那麼,每次「更改文件內容[如write()寫入數據]」時,都會將這些改變同步到基礎存儲設備上。
當模式是 "rw" 並且 操作的是基礎存儲設備上的文件;那麼,關閉文件時,會將「文件內容的修改」同步到基礎存儲設備上。至於,「更改文件內容」時,是否會立即同步,取決於系統底層實現。

3. 演示程序

源碼如下:

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.PrintStream;;
import java.io.RandomAccessFile;
import java.io.IOException;

/**
* RandomAccessFile 測試程序
*
* 運行結果(輸出如下):
* c1=a
* c2=b
* buf=9876543210
*
* 此外,
* (01) 在源文件所在目錄生成了file.txt。
* (02) 注意RandomAccessFile寫入boolean, byte, char, int,所佔的字符個數。
*
*/
public class RandomAccessFileTest {

private static final String FileName = "file.txt";

public static void main(String[] args) {
// 若文件「file.txt」存在,則刪除該文件。
File file = new File(FileName);
if (file.exists())
file.delete();

testCreateWrite();
testAppendWrite();
testRead();
}

/**
* 若「file.txt」不存在的話,則新建文件,並向文件中寫入內容
*/
private static void testCreateWrite() {
try {
// 創建文件「file.txt」對應File對象
File file = new File(FileName);
// 創建文件「file.txt」對應的RandomAccessFile對象
RandomAccessFile raf = new RandomAccessFile(file, "rw");

// 向「文件中」寫入26個字母+回車
raf.writeChars("abcdefghijklmnopqrstuvwxyz\n");
// 向「文件中」寫入"9876543210"+回車
raf.writeChars("9876543210\n");

raf.close();
} catch(IOException e) {
e.printStackTrace();
}
}

/**
* 向文件末尾追加內容
*/
private static void testAppendWrite() {
try {
// 創建文件「file.txt」對應File對象
File file = new File(FileName);
// 創建文件「file.txt」對應的RandomAccessFile對象
RandomAccessFile raf = new RandomAccessFile(file, "rw");

// 獲取文件長度
long fileLen = raf.length();
// 將位置定位到「文件末尾」
raf.seek(fileLen);

// 以下向raf文件中寫數據
raf.writeBoolean(true); // 佔1個字節
raf.writeByte(0x41); // 佔1個字節
raf.writeChar('a'); // 佔2個字節
raf.writeShort(0x3c3c); // 佔2個字節
raf.writeInt(0x75); // 佔4個字節
raf.writeLong(0x1234567890123456L); // 佔8個字節
raf.writeFloat(4.7f); // 佔4個字節
raf.writeDouble(8.256);// 佔8個字節
raf.writeUTF("UTF嚴"); // UTF-8格式寫入
raf.writeChar('\n'); // 佔2個字符。「換行符」

raf.close();
} catch(IOException e) {
e.printStackTrace();
}
}

/**
* 通過RandomAccessFile讀取文件
*/
private static void testRead() {
try {
// 創建文件「file.txt」對應File對象
File file = new File(FileName);
// 創建文件「file.txt」對應的RandomAccessFile對象,以只讀方式打開
RandomAccessFile raf = new RandomAccessFile(file, "r");

// 讀取一個字符
char c1 = raf.readChar();
System.out.println("c1="+c1);
// 讀取一個字符
char c2 = raf.readChar();
System.out.println("c2="+c2);

// 跳過54個字節。
raf.seek(54);

// 測試read(byte[] buffer, int byteOffset, int byteCount)
byte[] buf = new byte[20];
raf.read(buf, 0, buf.length);
System.out.println("buf="+(new String(buf)));

raf.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}

運行結果:

c1=a
c2=b
buf=9876543210

結果說明:程序會在源文件所在目錄生成file.txt;file.txt的內容如下:

file.txt對應的16進位內容如下:

相關焦點

  • Java【IO系列】基礎篇—15. BufferedReader和BufferedWriter詳解
    示例代碼關於BufferedReader中API的詳細用法,參考示例代碼(BufferedReaderTest.java):import java.io.BufferedReader;import java.io.ByteArrayInputStream;import java.io.File;import java.io.InputStream;
  • Java【IO系列】基礎篇—6. FileInputStream和FileOutputStream詳解
    FileInputStream 和 FileOutputStream 介紹2. 示例程序1. FileInputStream 和 FileOutputStream 介紹FileInputStream 是文件輸入流,它繼承於InputStream。通常,我們使用FileInputStream從某個文件中獲得輸入字節。
  • 夯實Java基礎系列16:一文讀懂Java IO流和常見面試題
    = -1) { fileOutputStream.write(buffer); } RandomAccessFile randomAccessFile = new RandomAccessFile(new File("c.txt"), "rw");
  • Java【IO系列】基礎篇—9. DataInputStream和DataOutputStream
    示例代碼關於DataInputStream中API的詳細用法,參考示例代碼(DataInputStreamTest.java):import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.ByteArrayInputStream;import java.io.File
  • Java【IO系列】基礎篇—1. IO框架
    關於java的io部分,以前學習過。
  • Java Web安全 || Java基礎 · Java IO/NIO多種讀寫文件方式
    我們通常讀寫文件都是使用的阻塞模式,與之對應的也就是java.io.FileSystem。java.io.FileInputStream類提供了對文件的讀取功能,Java的其他讀取文件的方法基本上都是封裝了java.io.FileInputStream類,比如:java.io.FileReader。
  • Java File類(文件操作類)詳解
    在 Java 中,File 類是 java.io 包中唯一代表磁碟文件本身的對象,也就是說,如果希望在程序中操作文件和目錄,則都可以通過 File
  • 「JAVA」屬性、路徑分隔符有何不同?file對象創建,文件過濾器
    為解決這個問題,Java 在java.io.File類中提供了兩類常量,分別來表示路徑分隔符和屬性分隔符,官方源碼如下所示:java.io.File類 中的路徑分隔符和屬性屬性分隔符、路徑分隔符api文件過濾文件過濾器的存在,能夠很好的篩選出我們想要的文件;在Java中提供了java.io.FileFilter和java.io.FilenameFilter兩個文件過濾器,其中FilenameFilter過濾器值針對文件名稱提供過濾的
  • 「GCTT 出品」對 Go 中長時間運行 io.Reader 和 io.Writer 的操作...
    首發於:https://studygolang.com/articles/12547每當我們在使用類似 io.Copy 和 ioutil.ReadAll 的工具時,比如我們正在從 http.Response 主體讀入或者上傳一個文件,我們會發現這些方法將一直堵塞,直到整個過程完成,哪怕耗時數十分鐘甚至是小時——而且我們沒有辦法來查看進度
  • 50個常見的 Java 錯誤及避免方法(第三部分)
    「class file contains wrong class」當Java代碼嘗試在錯誤的目錄中尋找類文件時,就會出現「class file contains wrong class」的問題,導致類似於以下內容的錯誤消息:MyTest.java:10: cannot access MyStruct bad class file: D:JavatestMyStruct.java
  • 自從學會Java中的lambda表達式和函數式編程技巧,再也不用加班了!
    LambdaDemo.java (version 4)import java.io.File;import java.io.FileFilter;import java.nio.file.Files;import java.nio.file.FileSystem;import java.nio.file.FileSystems;import java.nio.file.FileVisitor
  • Java 非阻塞 IO 和異步 IO
    IO,也就是大家耳熟能詳的 NIO 和 AIO。package com.javadoop.aio;import java.io.IOException;import java.net.InetSocketAddress;import java.net.SocketAddress;import java.nio.ByteBuffer;import java.nio.channels.AsynchronousServerSocketChannel
  • 打工人打工魂,打工的必會java調用python的幾種用法
    interpreter = new PythonInterpreter(); interpreter.exec("a='hello world'; "); interpreter.exec("print a;"); }}2.在java中直接調用python腳本在本地的D盤創建一個python腳本,文件名字為javaPythonFile.py
  • 教你徹底學會Java序列化和反序列化
    序列化:對象序列化的最重要的作用是傳遞和保存對象的時候,保證對象的完整性和可傳遞性。方便字節可以在網絡上傳輸以及保存在本地文件。為什麼需要序列化和反序列化實現分布式核心在於RMI,可以利用對象序列化運行遠程主機上的服務,實現運行的時候,就像在本地上運行Java對象一樣。
  • 2015/2016JAVA試卷自製答案
    //接下來劃重點When the assertion is enable, aka, we run it with java -ea Example, it will print out 「Caught an error!」.
  • JAVA生成JPG縮略圖
    但是這種做法在客戶端看來就沒有那麼輕鬆了,對於撥號上網的用戶簡直是一場惡夢,雖然你可以在圖片區域設置wide和high!    問題的解決之道來了!我們可以在類中處理一張大圖,並縮小它。  前提是需要JDK1.4,這樣才能進行處理。
  • 關於java用字節流和字符流讀取文件的各種情況
    java讀取文件的方式1.字節流讀取:InputStream和OutPutStream,其讀取的方式按字節讀取,這個常用於讀取原始數據。2.字符流讀取:Reader和Writer,按字節讀取數據,java裡面一個字符對應兩個字節。
  • 每日一課 | Apache POI –用Java讀寫Excel文件
    XSSFWorkbook和HSSFWorkbook是充當Excel工作簿的類HSSFSheet和XSSFSheet是充當Excel工作表的類Row定義一個Excel行Cell定義參照行尋址的Excel單元格。
  • Python爬蟲 | 0xc - 數據存儲:CSV和Excel
    ):    with open(file_path, 'w+', newline='') as f:        writer = csv.writer(f)        for row in data_list:            writer.writerow(row)# writerows → 多行寫入def write_lines