使用文件

时间:2013-11-26 02:10:49

标签: java

我正在研究一个项目,并且有定义了从文件中写入和读取的函数,我的特殊问题是在系统正在读取文本文件时没有格式,这里有两个函数写入和读取文件;

public void writetofile()
{
    String bucky4[]={custname,custlname,agee,address,id};
    for(int i = 0; i < bucky4.length; i++) {
         try (BufferedWriter bw = new BufferedWriter(new     FileWriter("records.txt", true))) {
             String s;
             s = bucky4[i];
             bw.write(s);
             bw.newLine();
             bw.flush();
         }

         catch(IOException ex) {
             JOptionPane.showMessageDialog(null, "Error In File");
         }
     }
}

public void filereader (){

     int i=0;
     Object[] options = {"OK"};
     try{
         FileInputStream in = new FileInputStream("records.txt");
         BufferedReader br = new BufferedReader(new InputStreamReader(in));
         String strLine;
         StringBuffer sb = new StringBuffer();

         while((strLine = br.readLine())!= null)
         {
             sb.append(strLine +"\n");
         }
         JOptionPane.showMessageDialog( null, sb.toString());
     }catch(Exception e){
         JOptionPane.showOptionDialog(null, "Error", "Customers",  JOptionPane.PLAIN_MESSAGE,JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
     }
  };

现在我的出局是这样的:

  

james
  blunt
  male
  18
  c-18-6 , kombo

我期待以这样的格式制作它们:

  

first name : james
  last name : blunt
  gender : male; ...

请考虑我不能使用构造函数,任何帮助表示赞赏

2 个答案:

答案 0 :(得分:0)

如果它总是以相同的顺序(名字,姓氏,性别......),您可以创建一个函数,使用StringTokenzier格式化输出字符串,以'\ n'字符溢出数据。然后,您可以使用StringBuffer"first name""last name"等将每行附加到"gender",然后返回结果。

public String format(String s){
    StringTokenizer st = new StringTokenizer(s, "\n");
    StringBuffer sb = new StringBuffer();
    sb.append("first name : " + st.nextToken() + '\n');
    sb.append("last name : " + st.nextToken() + '\n');
    sb.append("gender : " + st.nextToken() + '\n');
    ...
    return sb.toString();
}

答案 1 :(得分:0)

好吧,我已经定义了一个数组和一个简单的if和else而且它已经解决了,这里是代码段:

        public void filereader (){
        String[] titles = {"first name: ", "last name: ", "gender" ,"age","address","id"};
        int i=0;
        Object[] options = {"OK"};
        try
        {
        FileInputStream in = new FileInputStream("records.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;
        StringBuffer sb = new StringBuffer();

        while((strLine = br.readLine())!= null)
       {
        sb.append(titles[i]+ strLine +"\n");
              if (i == 5) { 
                   i=0;
               } else
               { i++; };
                 }
              JOptionPane.showMessageDialog( null, sb.toString());
               }catch(Exception e){
              JOptionPane.showOptionDialog(null, "Error", "Customers",   JOptionPane.PLAIN_MESSAGE,JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
               }

             }