print打印字符串之谜
生活随笔
收集整理的這篇文章主要介紹了
print打印字符串之谜
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
2019獨角獸企業(yè)重金招聘Python工程師標準>>>
print打印字符串之謎 博客分類: javastring 中維護了一個char數(shù)組的value值,打印的時候也就是打印的這個數(shù)組的值。但是print(str)參數(shù)為string類型
?
看print的源碼
?
/*** Prints a String and then terminate the line. This method behaves as* though it invokes <code>{@link #print(String)}</code> and then* <code>{@link #println()}</code>.** @param x The <code>String</code> to be printed.*/public void println(String x) {synchronized (this) {print(x);newLine();}}? ? public void print(String s) {
if (s == null) {s = "null";}write(s);}? ? private void write(String s) {
try {synchronized (this) {ensureOpen();textOut.write(s);//java.io.BufferedWriter.write(s)textOut.flushBuffer();charOut.flushBuffer();//java.io.OutputStreamWriter.flushBuffer();if (autoFlush && (s.indexOf('\n') >= 0))out.flush();}}?//在看看write方法調(diào)用了getChars方法,這是輸出string,char數(shù)組值的關鍵
public void write(String s, int off, int len) throws IOException {synchronized (lock) {ensureOpen();int b = off, t = off + len;while (b < t) {int d = min(nChars - nextChar, t - b);s.getChars(b, b + d, cb, nextChar);b += d;nextChar += d;if (nextChar >= nChars)flushBuffer();}}}? ?//最終調(diào)用了printStream方法的write方法
public void write(byte buf[], int off, int len) {try {synchronized (this) {ensureOpen();out.write(buf, off, len);if (autoFlush)out.flush();//關鍵在這一步調(diào)用了java.io.BufferedOutputStream的flushBuffer方法}}catch (InterruptedIOException x) {Thread.currentThread().interrupt();}??java.io.BufferedOutputStream的flushBuffer方法
/** Flush the internal buffer */最終調(diào)用了java.io.FileOutputStream..write(buf, 0, count);方法private void flushBuffer() throws IOException {if (count > 0) {out.write(buf, 0, count);//java.io.FileOutputStream..write(buf, 0, count);count = 0;}}? ? //?java.io.FileOutputStream..write最終調(diào)用了writeBytes方法
public void write(byte b[], int off, int len) throws IOException {writeBytes(b, off, len);}??//writeBytesa方法是本地方法最終以byte數(shù)組輸出
private native void writeBytes(byte b[], int off, int len) throws IOException;? ?jdK native code
??JNIEXPORT void JNICALL
Java_java_io_FileOutputStream_writeBytes(JNIEnv *env,jobject this, jbyteArray bytes, jint off, jint len) {jboolean append = (*env)->GetBooleanField(env, this, fos_append);FD fd = GET_FD(this, fos_fd);if (fd == -1) {JNU_ThrowIOException(env, "Stream Closed");return;}if (append == JNI_TRUE) {if (IO_Lseek(fd, 0L, SEEK_END) == -1) {JNU_ThrowIOExceptionWithLastError(env, "Append failed");}}writeBytes(env, this, bytes, off, len, fos_fd); }轉載于:https://my.oschina.net/xiaominmin/blog/1598168
總結
以上是生活随笔為你收集整理的print打印字符串之谜的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ActiveMQ的消息重发策略和DLQ处
- 下一篇: CentOS6.5升级到CentOS7