Java Code Examples for java.io.File.length()

The following are Jave code examples for showing how to use length() of the java.io.File class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: MVP-Practice-Project-Template   File: DataHelper.java   View Source Code Vote up 6 votes
/**
 * 使用递归获取目录文件大小
 */
public static long getDirSize(File dir) {
    if (dir == null) {
        return 0;
    }
    if (!dir.isDirectory()) {
        return 0;
    }
    long dirSize = 0;
    File[] files = dir.listFiles();
    for (File file : files) {
        if (file.isFile()) {
            dirSize += file.length();
        } else if (file.isDirectory()) {
            dirSize += file.length();
            dirSize += getDirSize(file); // 递归调用继续统计
        }
    }
    return dirSize;
}
 
Example 2
Project: eZooKeeper   File: ZnodeNewWizardComposite1.java   View Source Code Vote up 6 votes
@Override
public byte[] getZnodeData() throws Exception {
    Text filePathText = (Text) getControl(CONTROL_NAME_DATA_FILE_TEXT);
    String filePath = filePathText.getText();
    File file = new File(filePath);
    String fileName = file.getName();
    if (!file.exists()) {
        throw new IOException("File '" + fileName + "' does not exist.");
    }

    if (!file.isFile()) {
        throw new IOException("Path '" + filePath + "' is not a valid file.");
    }

    long length = file.length();

    if (length > Znode.MAX_DATA_SIZE) {
        throw new Exception("File '" + fileName
                + "' size is greater than the maximum allowed Znode data size (" + Znode.MAX_DATA_SIZE
                + " bytes).");
    }

    FileEditor fileEditor = new FileEditor(file);
    return fileEditor.read();
}
 
Example 3
Project: cas-5.1.0   File: AbstractResourceBasedServiceRegistryDao.java   View Source Code Vote up 6 votes
/**
 * Load registered service from file.
 *
 * @param file the file
 * @return the registered service, or null if file cannot be read, is not found, is empty or parsing error occurs.
 */
@Override
public RegisteredService load(final File file) {
    if (!file.canRead()) {
        LOGGER.warn("[{}] is not readable. Check file permissions", file.getName());
        return null;
    }

    if (!file.exists()) {
        LOGGER.warn("[{}] is not found at the path specified", file.getName());
        return null;
    }

    if (file.length() == 0) {
        LOGGER.debug("[{}] appears to be empty so no service definition will be loaded", file.getName());
        return null;
    }

    try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(file))) {
        return this.registeredServiceSerializer.from(in);
    } catch (final Exception e) {
        LOGGER.error("Error reading configuration file [{}]", file.getName(), e);
    }
    return null;
}
 
Example 4
Project: incubator-netbeans   File: FileObjects.java   View Source Code Vote up 6 votes
@NonNull
public static byte[] asBytes(@NonNull final File file) throws IOException {
    byte[] data = new byte[(int)file.length()];
    final InputStream in = new BufferedInputStream(new FileInputStream(file));
    try {
        int read, len = 0;
        while ((read=in.read(data, len, data.length-len))>0) {
            len+=read;
        }
        if (len != data.length) {
            data = Arrays.copyOf(data, len);
        }
    } finally {
        in.close();
    }
    return data;
}
 
Example 5
Project: MontageCam   File: FileUtil.java   View Source Code Vote up 6 votes
/**
 * 将图片文件加入到相册
 *
 * @param context
 * @param dstPath
 */
public static void ablumUpdate(final Context context, final String dstPath) {
    if (TextUtils.isEmpty(dstPath) || context == null)
        return;

    File file = new File(dstPath);
    //System.out.println("panyi  file.length() = "+file.length());
    if (!file.exists() || file.length() == 0) {//文件若不存在  则不操作
        return;
    }

    ContentValues values = new ContentValues(2);
    String extensionName = getExtensionName(dstPath);
    values.put(MediaStore.Images.Media.MIME_TYPE, "image/" + (TextUtils.isEmpty(extensionName) ? "jpeg" : extensionName));
    values.put(MediaStore.Images.Media.DATA, dstPath);
    context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}
 
Example 6
Project: keepass2android   File: Util.java   View Source Code Vote up 6 votes
static byte[] fromFile(String _file) throws IOException {
  _file = checkTilde(_file);
  File file = new File(_file);
  FileInputStream fis = new FileInputStream(_file);
  try {
    byte[] result = new byte[(int)(file.length())];
    int len=0;
    while(true){
      int i=fis.read(result, len, result.length-len);
      if(i<=0)
        break;
      len+=i;
    }
    fis.close();
    return result;
  }
  finally {
    if(fis!=null)
      fis.close();
  }
}
 
Example 7
Project: Pluto-Android   File: FileUtils.java   View Source Code Vote up 6 votes
/**
 * 获取目录文件大小
 * @param dir
 * @return
 */
public static long getDirSize(File dir) {
	if (dir == null) {
		return 0;
	}
    if (!dir.isDirectory()) {
    	return 0;
    }
    long dirSize = 0;
    File[] files = dir.listFiles();
    for (File file : files) {
    	if (file.isFile()) {
    		dirSize += file.length();
    	} else if (file.isDirectory()) {
    		dirSize += file.length();
    		dirSize += getDirSize(file); //递归调用继续统计
    	}
    }
    return dirSize;
}
 
Example 8
Project: Cable-Android   File: MultiDeviceContactUpdateJob.java   View Source Code Vote up 6 votes
private void sendUpdate(SignalServiceMessageSender messageSender, File contactsFile, boolean complete)
    throws IOException, UntrustedIdentityException, NetworkException
{
  if (contactsFile.length() > 0) {
    FileInputStream               contactsFileStream = new FileInputStream(contactsFile);
    SignalServiceAttachmentStream attachmentStream   = SignalServiceAttachment.newStreamBuilder()
                                                                              .withStream(contactsFileStream)
                                                                              .withContentType("application/octet-stream")
                                                                              .withLength(contactsFile.length())
                                                                              .build();

    try {
      messageSender.sendMessage(SignalServiceSyncMessage.forContacts(new ContactsMessage(attachmentStream, complete)));
    } catch (IOException ioe) {
      throw new NetworkException(ioe);
    }
  }
}
 
Example 9
Project: mininoteview   File: MyUtil.java   View Source Code Vote up 5 votes
static int getChiSize(File aFile)
{
	if(!aFile.exists() || (aFile.length() < 32) || (aFile.length() % 8 != 0))
		return -1;
	byte[] data = new byte[8];
	try
	{
		FileInputStream f_ins = new FileInputStream(aFile);
		int l = f_ins.read(data, 0, 8);
		f_ins.close();

		if(l != 8)
			return -1;

		String header = new String(data, 0, 4);
		if(!header.equals(CHIHEADER))
			return -1;
		int size = ByteBuffer.wrap(data, 4, 4).order(ByteOrder.LITTLE_ENDIAN).getInt();
		long k = size & 0xFFFFFFFFL;
		if(k < 0 || k > MAXFILESIZE) // 4 MiB limit
			return -1;
		return size;
	}
	catch(Exception e)
	{
		return -1;
	}
}
 
Example 10
Project: Panako   File: Store.java   View Source Code Vote up 5 votes
private boolean checkFile(File file){
	boolean fileOk = false;
	//file must be smaller than a configured number of bytes
	if(file.length() != 0 && file.length() < Config.getInt(Key.MAX_FILE_SIZE)){
		fileOk = true;
	}else{
		String message = "Could not process " + file.getName() + " it has an unacceptable file size: zero or larger than " + Config.getInt(Key.MAX_FILE_SIZE) + "bytes ).";
		LOG.warning(message);
		System.out.println(message);
	}
	return fileOk;
}
 
Example 11
Project: hadoop   File: TestLineRecordReader.java   View Source Code Vote up 5 votes
@Test
public void testMultipleClose() throws IOException {
  URL testFileUrl = getClass().getClassLoader().
      getResource("recordSpanningMultipleSplits.txt.bz2");
  assertNotNull("Cannot find recordSpanningMultipleSplits.txt.bz2",
      testFileUrl);
  File testFile = new File(testFileUrl.getFile());
  Path testFilePath = new Path(testFile.getAbsolutePath());
  long testFileSize = testFile.length();
  Configuration conf = new Configuration();
  conf.setInt(org.apache.hadoop.mapreduce.lib.input.
      LineRecordReader.MAX_LINE_LENGTH, Integer.MAX_VALUE);
  FileSplit split = new FileSplit(testFilePath, 0, testFileSize,
      (String[])null);

  LineRecordReader reader = new LineRecordReader(conf, split);
  LongWritable key = new LongWritable();
  Text value = new Text();
  //noinspection StatementWithEmptyBody
  while (reader.next(key, value)) ;
  reader.close();
  reader.close();

  BZip2Codec codec = new BZip2Codec();
  codec.setConf(conf);
  Set<Decompressor> decompressors = new HashSet<Decompressor>();
  for (int i = 0; i < 10; ++i) {
    decompressors.add(CodecPool.getDecompressor(codec));
  }
  assertEquals(10, decompressors.size());
}
 
Example 12
Project: ViewDebugHelper   File: CrashHandler.java   View Source Code Vote up 5 votes
public static void writeToFile(String fileName, String msg) throws IOException {
    File file=new File(fileName);
    if(file.exists()&&file.length()>1024*1024*5){//>5M
        file.delete();
    }
    if(!file.exists())
        file.createNewFile();
    RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
    long fileLength = randomFile.length();
    randomFile.seek(fileLength);
    randomFile.write(msg.getBytes());
    randomFile.close();
}
 
Example 13
Project: marathonv5   File: DisplayWindow.java   View Source Code Vote up 5 votes
@Override public void handleModule(ModuleInfo moduleInfo) {
    File moduleFile = new File(moduleInfo.getModuleDirElement().getFile(), moduleInfo.getFileName());
    int offset = 0;
    try {
        boolean fileExists = moduleFile.exists();
        addImportStatement(moduleFile, fileExists);
        if (fileExists && canAppend(moduleFile)) {
            offset = (int) moduleFile.length();
        }
        FileWriter writer = new FileWriter(moduleFile, true);
        writer.write((offset > 0 ? EOL : "")
                + getModuleHeader(moduleInfo.getModuleFunctionName(), moduleInfo.getModulefunctionDescription()));
        writer.close();
        fileUpdated(moduleFile);
        Platform.runLater(new Runnable() {
            @Override public void run() {
                openFile(moduleFile);
            }
        });
        final int o = offset;
        Platform.runLater(new Runnable() {
            @Override public void run() {
                currentEditor.setCaretPosition(scriptModel.getLinePositionForInsertionModule() + o);
            }
        });
        resetModuleFunctions();
        return;
    } catch (IOException e) {
        e.printStackTrace();
        FXUIUtils.showMessageDialog(DisplayWindow.this, "IOError: " + e.getMessage(), "Error", AlertType.ERROR);
        return;
    }
}
 
Example 14
Project: exam   File: AttachmentController.java   View Source Code Vote up 5 votes
@Restrict({@Group("TEACHER"), @Group("ADMIN")})
public Result addAttachmentToExam() {
    MultipartFormData<File> body = request().body().asMultipartFormData();
    FilePart<File> filePart = body.getFile("file");
    if (filePart == null) {
        return notFound();
    }
    File file = filePart.getFile();
    if (file.length() > AppUtil.getMaxFileSize()) {
        return forbidden("sitnet_file_too_large");
    }
    Map<String, String[]> m = body.asFormUrlEncoded();
    Long eid = Long.parseLong(m.get("examId")[0]);
    Exam exam = Ebean.find(Exam.class, eid);
    if (exam == null) {
        return notFound();
    }
    User user = getLoggedUser();
    if (!user.hasRole(Role.Name.ADMIN.toString(), getSession()) && !exam.isOwnedOrCreatedBy(user)) {
        return forbidden("sitnet_error_access_forbidden");
    }
    String newFilePath;
    try {
        newFilePath = copyFile(file, "exam", eid.toString());
    } catch (IOException e) {
        return internalServerError("sitnet_error_creating_attachment");
    }
    // Delete existing if exists
    removePrevious(exam);

    Attachment attachment = createNew(filePart, newFilePath);
    exam.setAttachment(attachment);
    exam.save();
    return ok(attachment);
}
 
Example 15
Project: boohee_v5.6   File: IndexReader.java   View Source Code Vote up 4 votes
public LongIndexReader(File indexFile) throws IOException {
    this(new SimpleBufferedRandomAccessInputStream(new RandomAccessFile(indexFile, "r")), 0, indexFile.length());
    this.indexFile = indexFile;
    open();
}
 
Example 16
Project: GitHub   File: FileDownloadUtils.java   View Source Code Vote up 4 votes
public static boolean isBreakpointAvailable(final int id, final FileDownloadModel model,
                                            final String path,
                                            final Boolean outputStreamSupportSeek) {
    boolean result = false;

    do {
        if (path == null) {
            if (FileDownloadLog.NEED_LOG) {
                FileDownloadLog.d(FileDownloadUtils.class, "can't continue %d path = null", id);
            }
            break;
        }

        File file = new File(path);
        final boolean isExists = file.exists();
        final boolean isDirectory = file.isDirectory();

        if (!isExists || isDirectory) {
            if (FileDownloadLog.NEED_LOG) {
                FileDownloadLog.d(FileDownloadUtils.class, "can't continue %d file not suit, exists[%B], directory[%B]",
                        id, isExists, isDirectory);
            }
            break;
        }

        final long fileLength = file.length();
        final long currentOffset = model.getSoFar();

        if (model.getConnectionCount() <= 1 && currentOffset == 0) {
            // the sofar is stored on connection table
            if (FileDownloadLog.NEED_LOG) {
                FileDownloadLog.d(FileDownloadUtils.class, "can't continue %d the downloaded-record is zero.",
                        id);
            }
            break;
        }

        final long totalLength = model.getTotal();
        if (fileLength < currentOffset ||
                (totalLength != TOTAL_VALUE_IN_CHUNKED_RESOURCE  // not chunk transfer encoding data
                        &&
                        (fileLength > totalLength || currentOffset >= totalLength))
                ) {
            // dirty data.
            if (FileDownloadLog.NEED_LOG) {
                FileDownloadLog.d(FileDownloadUtils.class, "can't continue %d dirty data" +
                                " fileLength[%d] sofar[%d] total[%d]",
                        id, fileLength, currentOffset, totalLength);
            }
            break;
        }

        if (outputStreamSupportSeek != null && !outputStreamSupportSeek &&
                totalLength == fileLength) {
            if (FileDownloadLog.NEED_LOG) {
                FileDownloadLog.d(FileDownloadUtils.class, "can't continue %d, because of the " +
                                "output stream doesn't support seek, but the task has already " +
                                "pre-allocated, so we only can download it from the very beginning.",
                        id);
            }
            break;
        }

        result = true;
    } while (false);


    return result;
}
 
Example 17
Project: bdf2   File: PdfToSwfConverter.java   View Source Code Vote up 4 votes
public String execute(String sourcePdf, String targetSwf) throws Exception {
	if (!StringUtils.isNotEmpty(sourcePdf) || !new File(sourcePdf).exists()) {
		throw new IllegalAccessException("pdf文件不存在!");
	}
	if (!StringUtils.isNotEmpty(targetSwf)) {
		targetSwf = sourcePdf.substring(0, sourcePdf.length() - 4) + ".swf";
	}

	if (!StringUtils.isNotEmpty(pdfToSwfPath)) {
		throw new RuntimeException("请先在dorado-home/configure.properties文件中配置bdf2.swfviewer.pdfToSwf属性值");
	}
	if (!StringUtils.isNotEmpty(xpdfPath)) {
		throw new RuntimeException("请先在dorado-home/configure.properties文件中配置bdf2.swfviewer.xpdfPath属性值");
	}

	sourcePdf = "\"" + sourcePdf + "\"";
	targetSwf = "\"" + targetSwf + "\"";

	log.info("sourcePdf path:" + sourcePdf);
	log.info("targetSwf path:" + targetSwf);
	Process process = null;
	File pdf = new File(sourcePdf);
	long pdfSize = pdf.length() / (1024 * 1024);// 单位M
	if (isWindows()) {
		StringBuffer command = new StringBuffer(pdfToSwfPath + " " + sourcePdf);
		if (pdfSize > 1) {// 文件大于1M时,添加该参数增加转换效率
			command.append(" -s poly2bitmap");
		}
		command.append(" -s languagedir=" + xpdfPath + "" + " -T 9 -o " + targetSwf);
		process = Runtime.getRuntime().exec(command.toString());
	} else {
		String[] cmd = null;
		if (pdfSize > 1) {
			cmd = new String[10];
			cmd[0] = pdfToSwfPath;
			cmd[1] = sourcePdf;
			cmd[2] = "-s";
			cmd[3] = "poly2bitmap";
			cmd[4] = "-s";
			cmd[5] = "languagedir=" + xpdfPath + "";
			cmd[6] = "-T";
			cmd[7] = "9";
			cmd[8] = "-o";
			cmd[9] = targetSwf;
		} else {
			cmd = new String[8];
			cmd[0] = pdfToSwfPath;
			cmd[1] = sourcePdf;
			cmd[2] = "-s";
			cmd[3] = "languagedir=" + xpdfPath + "";
			cmd[4] = "-T";
			cmd[5] = "9";
			cmd[6] = "-o";
			cmd[7] = targetSwf;
		}
		process = Runtime.getRuntime().exec(cmd);
	}

	new DoOutput(process.getInputStream()).start();
	new DoOutput(process.getErrorStream()).start();
	process.waitFor();
	return targetSwf;
}
 
Example 18
Project: neoscada   File: PipeServiceImpl.java   View Source Code Vote up 4 votes
public Long fetchNextEvents ( final String pipeName, final int max, final List<File> result )
{
    final File dir = getQueueDir ( pipeName );

    final File[] files = dir.listFiles ();
    Arrays.sort ( files );

    final long now = System.currentTimeMillis ();

    Long endTime = null;

    for ( final File file : files )
    {
        if ( !file.isFile () || !file.canRead () )
        {
            continue;
        }
        if ( file.getName ().endsWith ( ".evt" ) && file.length () > 0 )
        {
            logger.trace ( "Preparing: {}", file );

            final MetaInfo info = parse ( file.getName () );
            if ( info == null )
            {
                logger.info ( "Broken file name: {}", file.getName () );
                continue;
            }

            final long timestamp = info.timestamp;

            if ( timestamp > now )
            {
                if ( endTime == null || endTime > timestamp )
                {
                    if ( logger.isTraceEnabled () )
                    {
                        logger.trace ( "Setting end time to {} (in {} ms)", timestamp, timestamp - now );
                    }
                    endTime = timestamp;
                }
                logger.debug ( "Postponed item: {}", file.getName () );
                continue;
            }

            result.add ( file );
        }
        if ( max > 0 && result.size () > max )
        {
            // abort since we are full
            return endTime;
        }
    }

    return endTime;
}
 
Example 19
Project: Musicoco   File: DiskLruCache.java   View Source Code Vote up 4 votes
private synchronized void completeEdit(Editor editor, boolean success) throws IOException {
    Entry entry = editor.entry;
    if (entry.currentEditor != editor) {
        throw new IllegalStateException();
    }

    // if this edit is creating the entry for the first time, every index must have a value
    if (success && !entry.readable) {
        for (int i = 0; i < valueCount; i++) {
            if (!entry.getDirtyFile(i).exists()) {
                editor.abort();
                throw new IllegalStateException("edit didn't create file " + i);
            }
        }
    }

    for (int i = 0; i < valueCount; i++) {
        File dirty = entry.getDirtyFile(i);
        if (success) {
            if (dirty.exists()) {
                File clean = entry.getCleanFile(i);
                dirty.renameTo(clean);
                long oldLength = entry.lengths[i];
                long newLength = clean.length();
                entry.lengths[i] = newLength;
                size = size - oldLength + newLength;
            }
        } else {
            deleteIfExists(dirty);
        }
    }

    redundantOpCount++;
    entry.currentEditor = null;
    if (entry.readable | success) {
        entry.readable = true;
        journalWriter.write(CLEAN + ' ' + entry.key + entry.getLengths() + '\n');
        if (success) {
            entry.sequenceNumber = nextSequenceNumber++;
        }
    } else {
        lruEntries.remove(entry.key);
        journalWriter.write(REMOVE + ' ' + entry.key + '\n');
    }

    if (size > maxSize || journalRebuildRequired()) {
        executorService.submit(cleanupCallable);
    }
}
 
Example 20
Project: MetadataEditor   File: MP3File.java   View Source Code Vote up 3 votes
/**
 * Calculates hash with algorithm "MD5", "SHA-1" or SHA-256".
 * Hash is calculated EXCLUDING meta-data, like id3v1 or id3v2
 *
 * @return byte[] hash value in byte
 * @throws IOException
 * @throws InvalidAudioFrameException
 * @throws NoSuchAlgorithmException
 */

public byte[] getHash(String algorithm, int bufferSize) throws InvalidAudioFrameException, IOException, NoSuchAlgorithmException {
    File mp3File = getFile();
    long startByte = getMP3StartByte(mp3File);

    int id3v1TagSize = 0;
    if (hasID3v1Tag()) {
        ID3v1Tag id1tag = getID3v1Tag();
        id3v1TagSize = id1tag.getSize();
    }

    InputStream inStream = new FileInputStream(mp3File);

    byte[] buffer = new byte[bufferSize];

    MessageDigest digest = MessageDigest.getInstance(algorithm);

    inStream.skip(startByte);

    int read;
    long totalSize = mp3File.length() - startByte - id3v1TagSize;
    int pointer = buffer.length;

    while (pointer <= totalSize) {

        read = inStream.read(buffer);

        digest.update(buffer, 0, read);
        pointer += buffer.length;
    }
    read = inStream.read(buffer, 0, (int) totalSize - pointer + buffer.length);
    digest.update(buffer, 0, read);

    byte[] hash = digest.digest();


    return hash;
}