首页 新闻 会员 周边

Java FileInputStream 死循环

0
[已关闭问题] 关闭于 2021-02-05 08:06

Java "1.8.0_121"

这算是 JDK的bug吗?

public static void main(String[] args) throws FileNotFoundException {
		File root = new File("E:\\新建文件夹\\");
		File target = new File("E:\\新建文件夹\\Concatenate.txt");
		FileOutputStream out =null;;
		FileInputStream in = null;
			try {
				if (!target.exists()) {
					target.createNewFile();
				}
				out = new FileOutputStream(target);
				for (File item : root.listFiles()) {
					in = new FileInputStream(item);
					byte[] buffer = new byte[5];
					int read = 0;
					int count = 0;
					while ((read = in.read(buffer)) != -1) {
						out.write(buffer, 0, read);
						count ++;
						if(count == 3) {
							break;
						}
					}
					in.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				try {
				if (in != null)
					in.close();
				if (out != null)
					out.close();
				}catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
		}
	}

JDK源码

    /**
     * Reads up to <code>b.length</code> bytes of data from this input
     * stream into an array of bytes. This method blocks until some input
     * is available.
     *
     * @param      b   the buffer into which the data is read.
     * @return     the total number of bytes read into the buffer, or
     *             <code>-1</code> if there is no more data because the end of
     *             the file has been reached.
     * @exception  IOException  if an I/O error occurs.
     */
    public int read(byte b[]) throws IOException {
        return readBytes(b, 0, b.length);
    }

文件内容:

C# No.1 

读其他文件不会有问题,就读这个文件死循环,有人知到为啥吗?

遇到了这么个事

这样的,要写入的文件也在该文件夹下,然后要写入的文件前面不能有文件,不然会陷入死循环,我也不知道为啥会这样

echo_lovely的主页 echo_lovely | 小虾三级 | 园豆:1433
提问于:2021-02-04 20:56
< >
分享
所有回答(1)
0

因为它是在读取的文件夹里面,会导致 读到写入文件的时候,读完了之后写入,再去读的时候发现,有新的内容了(刚才写入的内容),就又读了一遍,然后就不断读,读了写,又读,又发现有新的,读了写,emmm

echo_lovely | 园豆:1433 (小虾三级) | 2021-02-05 08:06
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册