以下是我的程序的较长但已注释的代码:
public static void main(String args[])
{
//get path of dump file
Path directory = Paths.get("E:\\Temp\\");
try
{
Files.createDirectory(directory);
}
catch(FileAlreadyExistsException e)
{
System.err.println("Directory already exists.");
}
catch(IOException e)
{
System.err.println("Could not create directory.");
e.printStackTrace();
System.exit(1);
}
Path file = directory.resolve("dump.txt");
//set initial vars and get system properties
long gig = 1_073_741_824L;
String separator = System.lineSeparator();
FileSystem fs = FileSystems.getDefault();
Iterable<FileStore> fstores = fs.getFileStores();
//write data to file
try(WritableByteChannel wbc = Files.newByteChannel(file, CREATE, WRITE,TRUNCATE_EXISTING))
{
//write heading to file
ByteBuffer buf_1 = ByteBuffer.wrap(new String("*****FILE SYSTEM DATA*****" + separator + separator).getBytes());
wbc.write(buf_1);
//write file store information to file
for(FileStore store : fstores)
{
//set up empty string and formatter for it
String f_string = "";
Formatter f = new Formatter(f_string);
//fill f_string
f.format("\nStore: %-20s Format: %-5s Capacity: %5dGB Unallocated: %5dGB",
store.name(),
store.type(),
store.getTotalSpace()/gig,
store.getUnallocatedSpace()/gig);
//test
System.out.println(f_string);
//set up buffers
ByteBuffer buf = ByteBuffer.wrap(f_string.getBytes());
//write to file
wbc.write(buf);
f.close();
}
}
catch(IOException e)
{
e.printStackTrace();
}
}这个程序的目的是在我的系统上(当前)硬编码的位置创建一个名为"dump.txt“的.txt文件,其中包含关于我的文件系统的信息。我遇到的问题是,除了标题“*文件系统数据*”之外,没有任何东西写入到文件中,实际上,当我调试代码时,创建格式化程序和最终catch块之间的每一行都不会被单步执行。我尝试将这些数据写入文件的方式与将buf_1 (标题)写入文件的方式相同,因此我完全不知道为什么会发生这个问题。
任何建议都将不胜感激。
附注:我曾经考虑过使用Writer,但为了了解我自己的知识,我正在使用channel/buffer对象。但是,如果你知道一些特殊的原因,为什么作家会更好,请让我知道:)。
发布于 2015-08-16 19:05:45
在将格式化字符串写入文件之前,您没有将其分配给f_string。
而不是
String f_string = "";
Formatter f = new Formatter(f_string);
f.format("\nStore: %-20s Format: %-5s Capacity: %5dGB Unallocated: %5dGB",
store.name(),
store.type(),
store.getTotalSpace()/gig,
store.getUnallocatedSpace()/gig);;你应该有类似这样的东西:
Formatter f = new Formatter(f_string);
String f_string =
f.format("\nStore: %-20s Format: %-5s Capacity: %5dGB Unallocated: %5dGB",
store.name(),
store.type(),
store.getTotalSpace()/gig,
store.getUnallocatedSpace()/gig);;发布于 2015-08-16 19:07:45
Formatter并不像您想象的那样工作,但您实际上并不需要使用它。请改用String.format:
String f_string = String.format("\nStore: %-20s Format: %-5s Capacity: %5dGB Unallocated: %5dGB",
store.name(),
store.type(),
store.getTotalSpace()/gig,
store.getUnallocatedSpace()/gig);https://stackoverflow.com/questions/32034287
复制相似问题