Java 如何添加每个文件';s码?
我正在打印X目录中每个文件的文件大小,但我想知道如何添加它们? 这是我的密码Java 如何添加每个文件';s码?,java,Java,我正在打印X目录中每个文件的文件大小,但我想知道如何添加它们? 这是我的密码 import java.io.File; public class abcc { public static void main( String [] args ) { File nam = new File("C:\\Windows\\System32"); if(nam.exists() && !nam.isDirectory()) System.out.println(na
import java.io.File;
public class abcc {
public static void main( String [] args ) {
File nam = new File("C:\\Windows\\System32");
if(nam.exists() && !nam.isDirectory())
System.out.println(nam.getName() + " exists and is " + nam.length()/1024 + " kb");
else if (nam.isDirectory())
System.out.println("");
else
System.out.println("0 ");
if (nam.isDirectory()){
for( File f : nam.listFiles()){
System.out.println( f.length() );
}
}else if(nam.isFile()){
}}}
输出是这样的
1.
2.
3.
我如何得到这些数字之和的单个输出?
谢谢您需要将总和存储在变量中。所以为它声明一个变量,例如
int totalSize = 0;
在循环中,您需要为每个文件长度添加totalSize
:
totalSize += f.length();
最后打印输出。您需要一个总大小的变量,然后继续添加独立文件的大小。由于f.length()返回long,因此需要一个数据类型为long的变量。 我已经编辑了您的代码,现在看起来像:
import java.io.File;
public class abcc
{
public static void main( String [] args )
{
long total = 0;
File nam = new File("C:\\Windows\\System32");
if(nam.exists() && !nam.isDirectory())
System.out.println(nam.getName() + " exists and is " + nam.length()/1024 + " kb");
else if (nam.isDirectory())
System.out.println("");
else
System.out.println("0 ");
if (nam.isDirectory()){
for( File f : nam.listFiles()){
System.out.println( f.length() );
total = total+f.length();
}
}else if(nam.isFile()){
}
System.out.println("Total Size : "+total);
}
}
此代码在末尾显示文件的总大小。我建议使用递归子例程。以下是我的建议代码:
import java.io.File;
public class DirectoryScan {
public static void main(String[] args){
File toScan = new File("C:\\Windows\\System32");
System.out.println("Total size is: " + getSize(toScan)/1024 + " kb");
}
public static long getSize(File name){
if(name.isDirectory()){//if it is a directory, call this method on all the files in the directory.
long size = 0;
for( File f : name.listFiles()){
size += getSize(f);//get the size for the directory and add the size of that directory to the total size
}
return size;//return the size of this directory
}
else{
System.out.println(name.getName() + " exists and is " + name.length()/1024 + " kb");
return name.length();//return the filesize.
}
}
}
基本上,递归调用getSize(File)(针对每个文件夹/文件)并返回该文件夹/文件的大小。通过定义一个变量,并使用
+
?@user3550204,我请求您接受答案!