java中FileOutputStream的java writeline方法为什么可以接收String类型值呢?

一.引子  文件,作为常见的数据源。关于操作文件的字节流就是 FileInputStream & FileOutputStream。它们是Basic IO字节流中重要的实现类。二、FileInputStream源码分析
  FileInputStream源码如下:
* FileInputStream 从文件系统的文件中获取输入字节流。文件取决于主机系统。
比如读取图片等的原始字节流。如果读取字符流,考虑使用 FiLeReader。
public class FileInputStream extends InputStream{
/* 文件描述符类---此处用于打开文件的句柄 */
private final FileD
/* 引用文件的路径 */
private final S
/* 文件通道,NIO部分 */
private FileChannel channel = null;
private final Object closeLock = new Object();
private volatile boolean closed = false;
private static final ThreadLocal&Boolean& runningFinalize =
new ThreadLocal&&();
private static boolean isRunningFinalize() {
if ((val = runningFinalize.get()) != null)
return val.booleanValue();
return false;
/* 通过文件路径名来创建FileInputStream */
public FileInputStream(String name) throws FileNotFoundException {
this(name != null ? new File(name) : null);
/* 通过文件来创建FileInputStream */
public FileInputStream(File file) throws FileNotFoundException {
String name = (file != null ? file.getPath() : null);
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkRead(name);
if (name == null) {
throw new NullPointerException();
if (file.isInvalid()) {
throw new FileNotFoundException("Invalid file path");
fd = new FileDescriptor();
fd.incrementAndGetUseCount();
this.path =
open(name);
/* 通过文件描述符类来创建FileInputStream */
public FileInputStream(FileDescriptor fdObj) {
SecurityManager security = System.getSecurityManager();
if (fdObj == null) {
throw new NullPointerException();
if (security != null) {
security.checkRead(fdObj);
path = null;
fd.incrementAndGetUseCount();
/* 打开文件,为了下一步读取文件内容。native方法 */
private native void open(String name) throws FileNotFoundE
/* 从此输入流中读取一个数据字节 */
public int read() throws IOException {
Object traceContext = IoTrace.fileReadBegin(path);
int b = 0;
b = read0();
} finally {
IoTrace.fileReadEnd(traceContext, b == -1 ? 0 : 1);
/* 从此输入流中读取一个数据字节。native方法 */
private native int read0() throws IOE
/* 从此输入流中读取多个字节到byte数组中。native方法 */
private native int readBytes(byte b[], int off, int len) throws IOE
/* 从此输入流中读取多个字节到byte数组中。 */
public int read(byte b[]) throws IOException {
Object traceContext = IoTrace.fileReadBegin(path);
int bytesRead = 0;
bytesRead = readBytes(b, 0, b.length);
} finally {
IoTrace.fileReadEnd(traceContext, bytesRead == -1 ? 0 : bytesRead);
return bytesR
/* 从此输入流中读取最多len个字节到byte数组中。 */
public int read(byte b[], int off, int len) throws IOException {
Object traceContext = IoTrace.fileReadBegin(path);
int bytesRead = 0;
bytesRead = readBytes(b, off, len);
} finally {
IoTrace.fileReadEnd(traceContext, bytesRead == -1 ? 0 : bytesRead);
return bytesR
public native long skip(long n) throws IOE
/* 返回下一次对此输入流调用的方法可以不受阻塞地从此输入流读取(或跳过)的估计剩余字节数。 */
public native int available() throws IOE
/* 关闭此文件输入流并释放与此流有关的所有系统资源。 */
public void close() throws IOException {
synchronized (closeLock) {
if (closed) {
closed = true;
if (channel != null) {
fd.decrementAndGetUseCount();
channel.close();
int useCount = fd.decrementAndGetUseCount();
if ((useCount &= 0) || !isRunningFinalize()) {
public final FileDescriptor getFD() throws IOException {
if (fd != null) return
throw new IOException();
/* 获取此文件输入流的唯一FileChannel对象 */
publicFileChannel getChannel() {
synchronized(this) {
if(channel == null) {
channel = FileChannelImpl.open(fd, path, true, false, this);
fd.incrementAndGetUseCount();
privatestaticnativevoidinitIDs();
privatenativevoidclose0() throwsIOE
initIDs();
protected void finalize() throws IOException {
if((fd != null) &&
(fd != FileDescriptor.in)) {
runningFinalize.set(Boolean.TRUE);
} finally{
runningFinalize.set(Boolean.FALSE);
1. 三个核心方法
  三个核心方法,也就是Override(重写)了抽象类InputStream的read方法。int read() 方法,即
    public int read() throws IOException
  代码实现中很简单,一个try中调用本地native的read0()方法,直接从文件输入流中读取一个字节。IoTrace.fileReadEnd(),字面意思是防止文件没有关闭读的通道,导致读文件失败,一直开着读的通道,会造成内存泄露。
  int read(byte b[]) 方法,即
    public int read(byte b[]) throws IOException
  代码实现也是比较简单的,也是一个try中调用本地native的readBytes()方法,直接从文件输入流中读取最多b.length个字节到byte数组b中。
  int read(byte b[], int off, int len) 方法,即
    public int read(byte b[], int off, int len) throws IOException
  代码实现和 int read(byte b[])方法 一样,直接从文件输入流中读取最多len个字节到byte数组b中。2. 值得一提的native方法  上面核心方法中为什么实现简单,因为工作量都在native方法里面,即JVM里面实现了。native倒是不少一一列举吧:
    native void open(String name) // 打开文件,为了下一步读取文件内容
    native int read0() // 从文件输入流中读取一个字节
    native int readBytes(byte b[], int off, int len) // 从文件输入流中读取,从off句柄开始的len个字节,并存储至b字节数组内。
    native void close0() // 关闭该文件输入流及涉及的资源,比如说如果该文件输入流的FileChannel对被获取后,需要对FileChannel进行close。
  其他还有值得一提的就是,在jdk1.4中,新增了NIO包,优化了一些IO处理的速度,所以在FileInputStream和FileOutputStream中新增了FileChannel getChannel()的方法。即获取与该文件输入流相关的 java.nio.channels.FileChannel对象。
FileOutputStream 源码如下:
* 文件输入流是用于将数据写入文件或者文件描述符类
比如写入图片等的原始字节流。如果写入字符流,考虑使用 FiLeWriter。
publicclassSFileOutputStream extendsOutputStream{
/* 文件描述符类---此处用于打开文件的句柄 */
private final FileD
/* 引用文件的路径 */
private final S
/* 如果为 true,则将字节写入文件末尾处,而不是写入文件开始处 */
private final boolean
/* 关联的FileChannel类,懒加载 */
private FileC
private final Object closeLock = new Object();
private volatile boolean closed = false;
private static final ThreadLocal&Boolean& runningFinalize =
new ThreadLocal&&();
private static boolean isRunningFinalize() {
if ((val = runningFinalize.get()) != null)
return val.booleanValue();
return false;
/* 通过文件名创建文件输入流 */
public FileOutputStream(String name) throws FileNotFoundException {
this(name != null ? new File(name) : null, false);
/* 通过文件名创建文件输入流,并确定文件写入起始处模式 */
public FileOutputStream(String name, boolean append)
throws FileNotFoundException
this(name != null ? new File(name) : null, append);
/* 通过文件创建文件输入流,默认写入文件的开始处 */
public FileOutputStream(File file) throws FileNotFoundException {
this(file, false);
/* 通过文件创建文件输入流,并确定文件写入起始处
public FileOutputStream(File file, boolean append)
throws FileNotFoundException
String name = (file != null ? file.getPath() : null);
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkWrite(name);
if (name == null) {
throw new NullPointerException();
if (file.isInvalid()) {
throw new FileNotFoundException("Invalid file path");
this.fd = new FileDescriptor();
this.append =
this.path =
fd.incrementAndGetUseCount();
open(name, append);
/* 通过文件描述符类创建文件输入流 */
public FileOutputStream(FileDescriptor fdObj) {
SecurityManager security = System.getSecurityManager();
if (fdObj == null) {
throw new NullPointerException();
if (security != null) {
security.checkWrite(fdObj);
this.fd = fdO
this.path = null;
this.append = false;
fd.incrementAndGetUseCount();
/* 打开文件,并确定文件写入起始处模式 */
private native void open(String name, boolean append)
throws FileNotFoundE
/* 将指定的字节b写入到该文件输入流,并指定文件写入起始处模式 */
private native void write(int b, boolean append) throws IOE
/* 将指定的字节b写入到该文件输入流 */
public void write(int b) throws IOException {
Object traceContext = IoTrace.fileWriteBegin(path);
int bytesWritten = 0;
write(b, append);
bytesWritten = 1;
} finally {
IoTrace.fileWriteEnd(traceContext, bytesWritten);
/* 将指定的字节数组写入该文件输入流,并指定文件写入起始处模式 */
private native void writeBytes(byte b[], int off, int len, boolean append)
throws IOE
/* 将指定的字节数组b写入该文件输入流 */
public void write(byte b[]) throws IOException {
Object traceContext = IoTrace.fileWriteBegin(path);
int bytesWritten = 0;
writeBytes(b, 0, b.length, append);
bytesWritten = b.
} finally {
IoTrace.fileWriteEnd(traceContext, bytesWritten);
/* 将指定len长度的字节数组b写入该文件输入流 */
public void write(byte b[], int off, int len) throws IOException {
Object traceContext = IoTrace.fileWriteBegin(path);
int bytesWritten = 0;
writeBytes(b, off, len, append);
bytesWritten =
} finally {
IoTrace.fileWriteEnd(traceContext, bytesWritten);
/* 关闭此文件输出流并释放与此流有关的所有系统资源 */
publicvoidclose() throwsIOException {
synchronized(closeLock) {
if(closed) {
closed = true;
if(channel != null) {
fd.decrementAndGetUseCount();
channel.close();
intuseCount = fd.decrementAndGetUseCount();
if((useCount &= 0) || !isRunningFinalize()) {
public final FileDescriptor getFD()
throws IOException {
if(fd != null)
thrownewIOException();
publicFile Channel getChannel() {
synchronized(this) {
if(channel == null) {
channel = FileChannelImpl.open(fd, path, false, true, append, this);
fd.incrementAndGetUseCount();
protected void finalize() throws IOException {
if(fd != null) {
if(fd == FileDescriptor.out || fd == FileDescriptor.err) {
runningFinalize.set(Boolean.TRUE);
} finally{
runningFinalize.set(Boolean.FALSE);
private native void close0() throws IOE
private static native void initIDs();
initIDs();
1. 三个核心方法
  三个核心方法,也就是Override(重写)了抽象类OutputStream的write方法。void write(int b) 方法,即
    public void write(intb) throws IOException
  代码实现中很简单,一个try中调用本地native的write()方法,直接将指定的字节b写入文件输出流。IoTrace.fileReadEnd()的意思和上面FileInputStream意思一致。  void write(byte b[]) 方法,即
    public void write(byteb[]) throws IOException
  代码实现也是比较简单的,也是一个try中调用本地native的writeBytes()方法,直接将指定的字节数组写入该文件输入流。
  void write(byte b[], int off, int len) 方法,即
    public void write(byte b[], int off, int len) throws IOException  代码实现和 void write(byte b[]) 方法 一样,直接将指定的字节数组写入该文件输入流。2. 值得一提的native方法
  上面核心方法中为什么实现简单,因为工作量都在native方法里面,即JVM里面实现了。native倒是不少一一列举吧:
    native void open(String name) // 打开文件,为了下一步读取文件内容
    native void write(int b, boolean append) // 直接将指定的字节b写入文件输出流
    native native void writeBytes(byte b[], int off, int len, boolean append) // 直接将指定的字节数组写入该文件输入流。
    native void close0() // 关闭该文件输入流及涉及的资源,比如说如果该文件输入流的FileChannel对被获取后,需要对FileChannel进行close。
阅读(...) 评论()Java 写文件:FileOutputStream
无论是二进制数据还是字符数据(文本数据)都可以用文件输出流 java.io.FileOutputStream 以字节流的方式保存到所指定文件。不过,如果写字符数据,FileWriter 更方便一些。FileWriter 除了提供了文件写入功能之外,还内置了字符编码功能。(关于 FileWriter 的使用,请参考本站相关文章)
java.io.FileOutputStream
类继承和重写了抽象类 java.io.OutputStream。他们两个都是从最早的JDK, JDK1.0就已经存在的类。
[父类 OutputStream]
抽象类 OutputStream 是所有字节输出流的基类,它共定义了一个构造方法和五个方法。构造方法什么也没做。在五个方法中,有,
三个 Write 方法:
public abstract void write(int b) throws IOException
向输出流里写入一个值为 b 的字节。需要注意的是,实际写入的是 int 类型 b 的低8位,其余的 24 位被忽略。
如果有错误,则抛出 IOException。调用这个方法时,需要捕获和处理 IOException。这个方法是OutputStream 类的唯一的抽象方法,需要具体类必须实现。一般的例程为参看下面示例程序。
public void write(byte[] b) throws IOException
向输入流里写入一个字节数组b。效果和 write(b, 0, b.length) 相同。调用这个方法时,需要捕获和处理 IOException。OutputStream 和 FileOutputStream 的实现都是调用了下面的方法。
public void write(byte[] b, int off, int len) throws IOException
把位置为 off、长度为len 的字节数组b中的数据写入到输出流中。OutputStream 的实现是反复调用write(int b), 子类应该提供更有效率的实现。如果 b 是 null, 则抛出NullPointerException 。如果off 或者 len 小于0,或者 off + len 大于数组 b 的长度, 则抛出 IndexOutOfBoundsException 。
FileOutputStream
重写了这个方法。
下面用一段例程演示 void write(int b) 和 void write(byte[] b) 的使用:
// TestFileOutputStream.java
import java.io.*;
public class TestFileOutputStream
public static void testWrite()
FileOutputStream fo = new FileOutputStream("MyOut.dat");
fo.write(0);
fo.write(0x43);
fo.write(0x44);
//fo.flush(); // 如果OutputStream 的实现使用了缓存,这个方法用于清空缓存里的数据,并通知底层去进行实际的写操作
// FileOutputStream 没有使用缓存,因此这个方法调用与否在这个例子的运行结果没有影响。
fo.close();
// 注意:如果用户忘记关闭打开的文件,系统可以通过 finalyze 方法在垃圾回收的时候替用户关闭这个流。
// 虽然如此,用户应该显示的调用这个方法。
}catch(IOException e)
e.printStackTrace();
public static void testWriteBytes()
// 构造一个要写的数据:
byte[] data = "这个例子测试文件写".getBytes("GB2312");
FileOutputStream fo = new FileOutputStream("MyOut1.data");
fo.write(data);
//fo.flush();
//如果OutputStream 的实现使用了缓存,这个方法用于清空缓存里的数据,并通知底层去进行实际的写操作
// FileOutputStream 没有使用缓存,因此这个方法调用与否在这个例子的运行结果没有影响。
fo.close();
}catch(Exception e)
e.printStackTrace();
public static void main(String[]args)
testWrite();
testWriteBytes();
其余两个方法
public void flush() throws IOException
如果OutputStream 的实现使用了缓存,这个方法用于清空缓存里的数据,并通知底层去进行实际的写操作。需要注意的是,这个缓存特指Java层的缓存。这个方法对底层(如操作系统)的缓存不起作用。参见 FileDescriptor。
OutputStream 中这个方法的实现什么也没做。具体子类应该重写这个方法。FileOutputStream 没有使用缓存,因此没有重写这个方法。因此,上面代码示例中,这个方法调用与否对运行结果没有影响。
public void close() throws
这个方法用于关闭流。虽然,如果用户忘记调用这个方法,系统可以通过 finalyze 方法在 OutputStream 对象垃圾回收的时候替用户关闭这个流。但用户应该养成良好的习惯显示的调用这个方法!
OutputStream 中这个方法的实现什么也没做。具体子类应该重写这个方法。java.io.FileOutputStream 重写了这个方法。 用于真正关闭相应的文件资源。
[FileOutputStream 的其他方法]:
java.io.FileOutputStream 除了重写 OutputStream 中上述四个方法之外,还提供了额外三个方法:
protected void finalize() throws
。这个方法其实是重写了
Object 中的这个方法(Object 是所有Java 类(包括数组类型)的“根级”父类)。这个方法是被 Java 虚拟机中的垃圾回收器调用的。用于 Java 对象已经不存在了但它占有的资源没有释放的情况。FileOutputStream 实现中,这个方法主要是调用了 close() 方法。上面例子中,如果用户没有调用 close() 方法,系统就通过这个方法在垃圾回收的时候关闭文件。但写程序时应该养成显示关闭文件的习惯。
public final
getFD() throws 。
这个方法返回 FileDescriptor
对象,这个对象表示这个文件流对应的文件系统中的实际文件。
关于 FD 的使用,请参见本站相关文章。
getChannel() 这是在 JDK1.4
中引入的方法。用于支持New IO 的特性。这个方法返回 FileChannel 对象,这个对象表示这个文件对应的文件系统中的通道。关于Channel 和 New IO,请参阅本站其它文章。
[关于 FileOutputStream 的构造]
FileOutputStream 提供了五个构造方法:
FileOutputStream(File file) throws FileNotFoundException
和 FileOutputStream(String name) throws
FileNotFoundException 都是通过实际文件路径(或其标识的File对象)来创建文件流。需要注意的是,如果文件不存在,(待查:是否会创建文件)。如果文件存在,则这两个构造方法中有打开文件的操作。如果文件给定的是目录而不是文件,或者文件不存在又不能创建,或者文件存在却不能打开,则抛出 FileNotFoundException 异常。如果文件由于安全保护而不允许读取,则抛出 SecurityException 异常。
写文件需要考虑的一个问题是,是从文件头写入(覆盖原有数据),还是从文件尾写入(增加数据)。上面的两个构造方法都是按照前者实现的,针对后者的情况,FileOutputStream 提供另外两个构造方法:
FileOutputStream(File file, boolean append) throws FileNotFoundException
和FileOutputStream(String name,
boolean append) throws FileNotFoundException
这两个构造方法多了一个 append 参数,如果参数值是 true, 则是“增加数据”,如果参数值是 false, 则是“覆盖原有数据”。即,退化成前两种构造方法。
最后,同 FileInputStream 一样, FileOutputStream 提供了用已经打开的文件来创建一个新的文件流:
public FileInputStream( fdObj)
这个构造方法里没有打开文件操作。输入的 FD 对应的一定是一个已经打开的文件。
[声明]:联系方式:
本文博主(gulibia):http://blog.sina.com.cn/s/blog_66e177dd0100hf92.html
没有更多推荐了,在java io 里面FileoutputStream的write方法写入的是一个int 默认是按照什么编码的,可以改变吗?_百度知道
在java io 里面FileoutputStream的write方法写入的是一个int 默认是按照什么编码的,可以改变吗?
我有更好的答案
这个方法其实是把数据变成字节码,就是序列化。编码是之后的一些对字节的操作处理,所以你这么问是不对的。改不了,除非你自己去改源码。
采纳率:38%
来自团队:
这个方法在Java源代码中最后是用native方法write(int b, boolean append)实现的,所以取决于你的平台
可以考虑使用BufferedReader的readLine来读取字符串,然后再转换成合适的编码。
为您推荐:
其他类似问题
fileoutputstream的相关知识
换一换
回答问题,赢新手礼包
个人、企业类
违法有害信息,请在下方选择后提交
色情、暴力
我们会通过消息、邮箱等方式尽快将举报结果通知您。Java如何自定义的byte[]数组写入文件_百度知道
Java如何自定义的byte[]数组写入文件
例如我自定义一个byte[]x = new byte[10];
我使用System.out,println();可以打印出它里面的每一个元素的默认值都是零,我想要把这些写进文件里面该如何做呢?我使用FileOutputStream里面的write(byte[])方法写进去的全是空值,什么都没有
我有更好的答案
public static void main(String[] args) throws IOException {//现在我有一个Byte[]byte[] bs = new byte[]{1,2,3,4,5};//确定写出文件的位置File file = new File(&Test.txt&);//建立输出字节流FileOutputStream fos = new FileOutputStream(file);//用FileOutputStream 的write方法写入字节数组fos.write(bs);System.out.println(&写入成功&);//为了节省IO流的开销,需要关闭fos.close();}}总结:因为你写入的是字节,所以会显示乱码。字节流就是这样的,用于读取文件和复制任何东西。
采纳率:68%
来自团队:
FileOutputStream.write(byte[] bytes)写入文件的是二进制码,你写入二进制1和0是不可见字符,必须用二进制/16进制文件格式打开才可以看到,
本回答被提问者采纳
贴上代码看看.write(byte[] b, int off, int len)用这个方法写写看。
额,文件的操作类当然不能做到,你直接加个循环然后把你想要赋的值给byte[i]就可以了
赋值过后写进去的是乱码呀?
其他1条回答
为您推荐:
其他类似问题
换一换
回答问题,赢新手礼包
个人、企业类
违法有害信息,请在下方选择后提交
色情、暴力
我们会通过消息、邮箱等方式尽快将举报结果通知您。一个outputStream的write方法的问题?
[问题点数:50分,结帖人dexter701]
本版专家分:244
结帖率 100%
CSDN今日推荐
本版专家分:244
本版专家分:122
本版专家分:244
本版专家分:122
本版专家分:122
本版专家分:0
匿名用户不能发表回复!|
其他相关推荐
OutputStream 写入文件(追加方式)
相信很多同学和我一样遇到过在通过服务器响应界面界面浏览器界面出现乱码的问题吧,今天我们就来思考一下如何解决乱码问题!
乱码产生的原因:
1.Servlet程序输出给浏览器的内容,不是任何一种中文字符集编码
2.浏览器浏览网页文档是所有采用的字符集编码与它接收到的中文字符集本身的字符编码不一致。
//response对象 因为getbytes对象获取的是gb2312的
package com.hanchao.
import java.io.BufferedInputS
import java.io.BufferedOutputS
import java.io.F
import java.io.FileInputS
import java.io.FileOutputS
最近使用java的FileOutputStream写文件,调用到了flush()方法。
于是查看了FileInputStream类的源代码,发现flush()其实是继承于其父类OutputStream的。
而OutputStream类的flush()却什么也没做,恍然大悟,真是“看源代码者得真相啊”。
其实flush()是Flushable接口的方法,官方文档的对该方法的注释是“Flushe
一,知识点1,首先不管是InputStream读read,还是OutputStream写write,都支持读写一定长度的byte[]。2,当然,还支持一个字节一个字节的读写,那么一个字节一个字节的读写,读出来的字节和写入的字节都是用的int类型的参数。3,int参数只会使用它的8个二进制位,也就是说类似于将int强行转换为byte,我感觉很无聊的设计,还不如直接用byte作为参数,这样搞是因为int
这两个流不能同时使用.
OutputStreamos=response.getOutputStream();
os.write(&hello,world&.getBytes());
PrintWriterout=response.getWriter();
out.println(&abc&);
java.lang.I
import java.io.IOE
import java.io.InputS
import java.io.OutputS
public class Demo {
public static void main(String[] args) {
//字节的输出输出流
InputStream is = Sy
package cn.itcast_01;
import java.io.FileOutputS
import java.io.IOE
* 字节输出流操作步骤:
A:创建字节输出流对象
B:调用write()方法
C:释放资源
* public void write(int b):写一个字节
* public vo
一、抽象类InputStream中主要用read()与read(byte[] b)这两个方法,JDK API中是这样描述两者的:
从输入流中读取数据的下一个字节,返回0到255范围内的int字节值。如果因为已经到达流末尾而没有可用的字节,则返回-1。在输入数据可用、检测到流末尾或者抛出异常前,此方法一直阻塞。
2. read(byte[] b)
从输入流中读取一
但凡程序想要输出内容,都可利用OutPutStream类完成
实现文件内容输出:
package cn.dujiang.import java.io.F
import java.io.FileOutputS
import java.io.OutputS
* 以下代码将字节数组的内容进行了输出,并且,如果此时要输出的文件不存在,那么会自动进行创建

我要回帖

更多关于 java writeline 的文章

 

随机推荐