编程相当新,读取和写入二进制文件时遇到麻烦。

时间:2017-02-14 22:53:22

标签: java arrays csv io

所以我有一个任务,我应该读一个.csv文件,然后把它写在一个单独的二进制文件中。 csv文件提供有关棒球运动员的奇怪格式的统计数据。

以下是实际运行程序的GUI代码:

import java.awt.*;
import javax.swing.*;
import java.util.*;
import java.io.*;

public class Homework3 extends JFrame
{
   private JButton jbChoose = new JButton("Choose File to Convert");
   private JTextArea jtaDisc = new JTextArea("Welcome to the .csv to binary file converter. Simply click the button below and choose the .csv file you would like to write to binary.", 5, 20);
   private File fobj = null;

   public static void main(String[] args)
   {
      new Homework3();
   }

   public Homework3()
   {
      this.setSize(400, 175);
      this.setTitle("File Converter");
      this.setLocationRelativeTo(null);
      this.setDefaultCloseOperation(EXIT_ON_CLOSE);
      this.setResizable(false);

      jtaDisc.setWrapStyleWord(true);
      jtaDisc.setLineWrap(true);
      jtaDisc.setEditable(false);

      JPanel jpSouth = new JPanel();
         jpSouth.add(jbChoose);
         jpSouth.setAlignmentX(jbChoose.CENTER_ALIGNMENT);
      this.add(jpSouth, BorderLayout.SOUTH);

      JPanel jpNorth = new JPanel();
         jpNorth.add(jtaDisc);
      this.add(jpNorth, BorderLayout.NORTH);

      Homework3Button hw3b = new Homework3Button(this);
         jbChoose.addActionListener(hw3b);

      setVisible(true);
   }
   public File getFobj()
   {
      return fobj;
   }

   public void setFobj(File _fobj)
   {
      fobj = _fobj;
   }
}

这是我实际尝试阅读和写作的课程。我已将它设置为打印出csv文件的值,以便我可以看到它出错的地方。出于某种原因,它正在阅读第一行并跳过第二行和第三行而不是像我想要的那样跳过第一行和第二行。它还远远不足以在write方法中实际创建文件。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import javax.swing.filechooser.*;
import java.util.*;

public class Homework3Button implements ActionListener 
{
   private Homework3 window;
   private ArrayList<Player> data = new ArrayList<Player>();
   private int pos; 

   public Homework3Button(Homework3 _window)
   {
      this.window = _window;
   }

   public void actionPerformed(ActionEvent ae)
   {
      doChoose();
      doRead();
      doWrite();
   }

   public void doChoose()
   {
      JFileChooser chooser = new JFileChooser(new File("."));
      FileNameExtensionFilter filter = new FileNameExtensionFilter("Excel Documents", "csv");
      chooser.setFileFilter(filter);

      int returnVal = chooser.showDialog(window, "Select");
      if(returnVal == JFileChooser.APPROVE_OPTION)
      {
         File fobj = chooser.getSelectedFile();
         window.setFobj(fobj);
      } 
   }

   public void doRead()
   {
      File fobj = window.getFobj();
      if(fobj == null)
      {
         JOptionPane.showMessageDialog(null, "There was a problem reading your file.", "Opening Error", JOptionPane.ERROR_MESSAGE);
         return;
      }
      BufferedReader br = null;
      try
      {
          br= new BufferedReader(new FileReader(fobj));
      }
      catch(IOException ioe)
      {
         JOptionPane.showMessageDialog(null, "Cannot open file: " + ioe.getMessage(), "Cannot Open", JOptionPane.ERROR_MESSAGE);
         return;
      }
      data = new ArrayList<Player>();
      try
      {
         String line = br.readLine() ;
         while(line != null)
         {
            System.out.println(line);
            for(int i = 0; i <= 1; i++)
            {
                line = br.readLine();
            }
            Player pl = new Player(line);
            data.add(pl);
            line = br.readLine();
         }
      }
      catch(EOFException eofe)
      {
         System.out.println("Exception for ArrayList.");
      } 
      catch(IOException ioe)
      {
         JOptionPane.showMessageDialog(null, "Error reading file: " + ioe.getMessage(), "Bad Read", JOptionPane.ERROR_MESSAGE);
         return;
      }
      try
      {
          br.close();
      }
      catch(IOException ioe)
      {
         JOptionPane.showMessageDialog(null, "Cannot close file: " + ioe.getMessage(), "Cannot Close", JOptionPane.ERROR_MESSAGE);
         return;
      }
   }

   public void doWrite()
   {
      File fobj2 = new File("BaseballNames1.bin");

      if(fobj2 == null)
      {
         JOptionPane.showMessageDialog(null, "There was a problem writing to your file.", "Problem Writing", JOptionPane.ERROR_MESSAGE);
         return;
      }
      DataOutputStream dos = null;
      try
      {
         dos = new DataOutputStream(new FileOutputStream(fobj2));
      }
      catch(IOException ioe)
      {
         JOptionPane.showMessageDialog(null, "Cannot open file: " + ioe.getMessage(), "Cannot Open", JOptionPane.ERROR_MESSAGE);
         return;
      }
      System.out.println("Before For Loop");
      for(Player pl : data)
      {
         System.out.println("Inside For Loop");
         try
         {
            dos.writeUTF(pl.getName());
            dos.writeUTF(pl.getBirth());
            dos.writeInt(pl.getWeight());
            dos.writeUTF(pl.getHeight());
         }
         catch(IOException ioe)
         {
            JOptionPane.showMessageDialog(null, "Cannot write file: " + ioe.getMessage(), "Cannot Write", JOptionPane.ERROR_MESSAGE);
            return;
         }
         try 
         {
            dos.close();
         }
         catch(IOException ioe)
         {
            JOptionPane.showMessageDialog(null, "Cannot close file: " + ioe.getMessage(), "Cannot Close", JOptionPane.ERROR_MESSAGE);
            return;
         }
      }
   }    
}

这是我描述玩家对象的类。当我尝试运行该程序时,在阅读.csv文件后,我遇到了一长串错误。最上面的一个是此类第16行的空指针异常。

import java.util.*;
import java.io.*;

public class Player
{
   private String firstName;
   private String lastName;
   private int birthDay;
   private int birthMonth;
   private int birthYear;
   private int weight;
   private double height;

   public Player(String lineRead)
   {
      String[] fields = lineRead.split(",");
      firstName = fields[0];
      lastName = fields[1];
      birthDay = Integer.parseInt(fields[2]);
      birthMonth = Integer.parseInt(fields[3]);
      birthYear = Integer.parseInt(fields[4]);
      weight = Integer.parseInt(fields[5]);
      height = Double.parseDouble(fields[6]);  
   }

   public String getName()
   {
      return firstName + " " + lastName;
   }

   public String getBirth()
   {
      return Integer.toString(birthMonth) + "/" + Integer.toString(birthDay) + "/" + Integer.toString(birthYear);
   }

   public int getWeight()
   {
      return weight;
   }

   public String getHeight()
   {
      String weight2 = String.format("%.2f", weight);
      return weight2;
   }
}

这是.csv文件格式,每行以前面的一个空格开头:

namefirst , namelast  , birthday , birthmonth , birthyear , weight , height 

Starlin   , Castro    ,24,3,1990,190,72.8
Madison   , Bumgarner ,1,8,1989,215,76.0
Jason     , Heyward   ,9,8,1989,240,77.3
Ruben     , Tejada    ,27,10,1989,160,71.2
Jenrry    , Mejia     ,11,10,1989,160,72.5
Mike      , Stanton   ,8,11,1989,235,77.9
Dayan     , Viciedo   ,10,3,1989,240,71.1
Chris     , Sale      ,30,3,1989,170,77.2
Freddie   , Freeman   ,12,9,1989,225,77.7
Clayton   , Kershaw   ,19,3,1988,225,75.4
Travis    , Snider    ,2,2,1988,235,72.0
Elvis     , Andrus    ,26,8,1988,200,72.0
Trevor    , Cahill    ,1,3,1988,220,76.0
Rick      , Porcello  ,27,12,1988,200,77.0
Brett     , Anderson  ,1,2,1988,235,76.5
Fernando  , Martinez  ,10,10,1988,200,73.0
Jhoulys   , Chacin    ,7,1,1988,215,75.2
Chris     , Tillman   ,15,4,1988,200,77.8
Neftali   , Feliz     ,2,5,1988,215,75.5
Craig     , Kimbrel   ,28,5,1988,205,71.6

我知道这很多,但我在网上看到的任何问题都与我的具体问题无关,javadocs对我来说真的很困惑。这是我使用Java IO的第一件大事,所以我非常感谢这里的一些帮助...我不确定这是否是我在该方面声明数组的方式的问题玩家类或什么...非常感谢任何关于如何解决这个混乱的建议。

1 个答案:

答案 0 :(得分:2)

你想跳过1行,但这会跳过两行:

for(int i = 0; i <= 1; i++)

此外,您的代码也不必要地复杂化,这样的事情更容易理解:

String line = br.readLine(); // read first line
br.readLine(); // skip 2nd line
while((line = br.readLine()) != null) // read the rest till the end
{
    System.out.println(line);
    Player pl = new Player(line);
    data.add(pl);
}