本文整理汇总了Java中java.io.File.length方法的典型用法代码示例。如果您正苦于以下问题:Java File.length方法的具体用法?Java File.length怎么用?Java File.length使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.io.File
的用法示例。
在下文中一共展示了File.length方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getDirSize
import java.io.File; //导入方法依赖的package包/类
/**
* 使用递归获取目录文件大小
*/
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;
}
示例2: getZnodeData
import java.io.File; //导入方法依赖的package包/类
@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();
}
示例3: load
import java.io.File; //导入方法依赖的package包/类
/**
* 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;
}
示例4: asBytes
import java.io.File; //导入方法依赖的package包/类
@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;
}
示例5: ablumUpdate
import java.io.File; //导入方法依赖的package包/类
/**
* 将图片文件加入到相册
*
* @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);
}
示例6: fromFile
import java.io.File; //导入方法依赖的package包/类
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();
}
}
示例7: getDirSize
import java.io.File; //导入方法依赖的package包/类
/**
* 获取目录文件大小
* @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;
}
示例8: sendUpdate
import java.io.File; //导入方法依赖的package包/类
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);
}
}
}
示例9: getChiSize
import java.io.File; //导入方法依赖的package包/类
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;
}
}
示例10: checkFile
import java.io.File; //导入方法依赖的package包/类
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;
}
示例11: testMultipleClose
import java.io.File; //导入方法依赖的package包/类
@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());
}
示例12: writeToFile
import java.io.File; //导入方法依赖的package包/类
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();
}
示例13: handleModule
import java.io.File; //导入方法依赖的package包/类
@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;
}
}
示例14: addAttachmentToExam
import java.io.File; //导入方法依赖的package包/类
@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);
}
示例15: LongIndexReader
import java.io.File; //导入方法依赖的package包/类
public LongIndexReader(File indexFile) throws IOException {
this(new SimpleBufferedRandomAccessInputStream(new RandomAccessFile(indexFile, "r")), 0, indexFile.length());
this.indexFile = indexFile;
open();
}