简体   繁体   English

如何格式化从java中的文件读取的数据

[英]How to Format data read from a file in java

I have a project that is meant to read and write data to and from a file and display it in a given format.For example, if the file was meant to hold contact information like name, age and phone number, i want to have output in the form of:我有一个项目,旨在从文件中读取和写入数据并以给定格式显示它。例如,如果文件旨在保存姓名、年龄和电话号码等联系信息,我想要输出形式如下:

    name : ****** , age: **, phone Number: ***.

How would i be able to do this?我怎么能做到这一点?

By the way here is the block of code meant to read the data from the file using the FileReader and BufferedReader classes.顺便说一下,这里是使用 FileReader 和 BufferedReader 类从文件中读取数据的代码块。

     while (line != null) {
            if (line.contains(name)) {
                data += line+"\n";
            }
            line = buff.readLine();
        }
        freader.close();
        buff.close();
        if(data.length() > 0){
        System.out.println("DATA FOUND! \n"+data);
        }else{
        System.out.println("DATA NOT FOUND");
        }

An straight forward and easy way of formatting a string in java is using the static method String.format() .在 java 中格式化字符串的一种直接而简单的方法是使用静态方法String.format() You can supply a format string and the coresponding arguments.您可以提供格式字符串和相应的参数。

So, for your example it would be:因此,对于您的示例,它将是:

String.format ("name : %s , age: %d, phone Number: %s.", name, age, phone);

For reading data you would have to write a parser to extract the data from each line.为了读取数据,您必须编写一个解析器来从每一行中提取数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM