【问题标题】:writing to a file using java.nio使用 java.nio 写入文件
【发布时间】:2013-03-27 17:25:33
【问题描述】:

我必须使用 java.nio 通过填充数据来创建任何所需大小的文件。我正在阅读文档,但对何时需要翻转、放置或书写并出现错误感到困惑。我已经使用 .io 成功完成了这个程序,但我正在测试 .nio 是否会使其运行得更快。

到目前为止,这是我的代码。 args[0] 是您要创建的文件的大小,args[1] 是要写入的文件的名称

public static void main(String[] args) throws IOException
 {
     nioOutput fp = new nioOutput();
     FileOutputStream fos = new FileOutputStream(args[1]);
     FileChannel fc = fos.getChannel();

     long sizeOfFile = fp.getFileSize(args[1]);      
     long desiredSizeOfFile = Long.parseLong(args[0]) * 1073741824; //1 Gigabyte = 1073741824 bytes      
     int byteLength = 1024;      
     ByteBuffer b = ByteBuffer.allocate(byteLength);

     while(sizeOfFile + byteLength < desiredSizeOfFile)
     {  
    // b.put((byte) byteLength);
     b.flip();
     fc.write(b);
     sizeOfFile += byteLength;       
     }
     int diff = (int) (desiredSizeOfFile - sizeOfFile);
     sizeOfFile += diff;

     fc.write(b, 0, diff);

     fos.close();
     System.out.println("Finished at " + sizeOfFile / 1073741824  + " Gigabyte(s)");                
 }

long getFileSize(String fileName) 
{
    File file = new File(fileName);        
    if (!file.exists() || !file.isFile()) 
    {
        System.out.println("File does not exist");
        return -1;
    }
    return file.length();
}

【问题讨论】:

  • 你遇到了什么错误?
  • 我收到b.put((byte) byteLength); 的错误
  • 您永远不会设置文件的大小。 nioOutput 类有什么作用?
  • @parsifal 它只是文件的名称
  • 不,文件名在args[1];至少,这是您用来打开文件的名称。并阅读FileOutputStream 的文档以了解我关于设置文件大小的早期评论。

标签: java io nio


【解决方案1】:

如果您只想用空值将文件预扩展为给定长度,您可以分三行完成并保存所有 I/O:

RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.setLength(desiredSizeOfFile);
raf.close();

这将像您现在尝试执行的操作一样快数倍。

【讨论】:

    【解决方案2】:

    对不起大家,我想通了。

     while(sizeOfFile + byteLength < desiredSizeOfFile)
         {           
         fc.write(b);
         b.rewind();
         sizeOfFile += byteLength;       
         }
         int diff = (int) (desiredSizeOfFile - sizeOfFile);
         sizeOfFile += diff;
    
         ByteBuffer d = ByteBuffer.allocate(diff);
    
         fc.write(d);
         b.rewind();
    
         fos.close();
         System.out.println("Finished at " + sizeOfFile / 1073741824  + " Gigabyte(s)");                
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-08
      • 1970-01-01
      • 1970-01-01
      • 2017-01-10
      • 1970-01-01
      • 2023-04-01
      • 2019-03-25
      • 2012-06-07
      相关资源
      最近更新 更多