我重写进程的run方法:while(true)将(i++)输出到文件D:\output.txt中
设置进程为daemon 运行。
然后发现 output.txt里面多了一串乱码,而且长度没有变化。
这是为什么?
不是设置成后台进程了吗?
我用的输出是                    OutputStream out=new FileOutputStream(f,true);
out.write((i++));
out.close();
为什么会出现乱码?

解决方案 »

  1.   

    out.write写入的应该是一个byte类型字节。
      

  2.   

    write(int c) 写入单个字符。 你要写int那就在后面加个""
    如:write(i+++"")
      

  3.   

    out.write 有两种参数 一个数byte数组 ,一个数int数。
    不过第二个是抽象方法,为什么我在这里也可以调用,不是说抽象方法要在子类实现才能用吗
      

  4.   

    out.write((i++));
    写入一个int,一个int是4个字节
    你想要文本,用out.write(String.valueOf(i++));
      

  5.   

    soga!那后台进程的问题又是什么原因呢?
      

  6.   

    我改成[code=java]out.write(Byte.parseByte(Integer.toString(i++)))[/cod还是乱码
      

  7.   


    刚刚试了一下,还是乱码
    怎么可能完整地贴一段代码出来
    PS:是soka不是soga
      

  8.   

    out.write(Byte.parseByte(Integer.toString(i++)))
    修改为
    out.write(new String((i++)+"","utf-8"))这有点太牵强,不过你试一试?
    最好贴出你的代码看看!
    如果还是乱码,我建议你把写入到记事本的反读取看看,是什么?
      

  9.   

    No! outputStream 不是用valueOf 而是用getByte 写入字节如果你想直接写入字符,请用FileWriter代码如下
    import java.io.*;
    class MyThread extends Thread
    {
    int i = 0;
    FileOutputStream fws = null;

    public MyThread()
    throws Exception
    {
    super();
    fws =new FileOutputStream("1.txt"); } public void run()
    {
    while (true)
    {
    try
    {
    byte[] buff = (""+(++i)).getBytes();
    fws.write(buff,0,buff.length);

    }
    catch (Exception e)
    {
    e.printStackTrace();
    }

    }
    }
    }public class DaemonThread 
    {
    public static void main(String[] args) 
    throws Exception
    {
    Thread thread = new MyThread();
    thread.setDaemon(true);
    thread.start();
    Thread.sleep(100); System.out.println("Hello World!");
    }
    }
      

  10.   

    fws.write(buff,0,buff.length);
    fws.flush();加个flush
      

  11.   

    代码如下class A implements Runnable{
    public void run(){
    int i=0;
    File f=new File ("D:\\output.txt");

    while (true){
    try {
    OutputStream out=new FileOutputStream(f,true);
    out.write(Byte.parseByte(Integer.toString(i++)));
    out.close();
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }
    }
      

  12.   


    Byte类static byte  parseByte(String s)Parses the string argument as a signed decimal byte.分析字符串是不是有个符号的byte如果是,就返回byte,否则引发NumberFormatException,我觉得你的程序应该到 128就异常了。
    这个函数并不是获得字符字节数组的函数!
      

  13.   

    OutputStream 的write写的是字符
    你要写string的话要用bufferedwriter
      

  14.   


    后台线程啊,你的main结束了,后台线程就结束了。
      

  15.   

    前台线程都结束了,后台线程就结束了。
    本程序,的前台线程只有main线程一个。 所以只有几十个数字输出。如果你要更多。你吧主线程阻塞住。不过小心磁盘暴了
      

  16.   

    哎呦我艹,上次帮另一位同学解决了一个类似的问题,当时应该是FileWriter。。这回是FileOutputStream啊。。看错看错。。
    不过不管是FileWriter还是FileOutputStream,都是古董了,用FileChannel吧!