当前位置: 首页 > 面试题库 >

如何让我的Java程序从文本文件读取日语(Unicode编码)?

霍锦
2023-03-14
问题内容

我遵循了《 Head First Java》一书中的示例程序,第14章第448-459页

通过Google图书,这是在线图书的链接:Head First
Java

我确保在操作系统(Windows 7)上安装了日语作为查看语言,并且当然要使用日语IME,以便首先输入日语。

我什至用unicode编码保存了文本文件。

我确定这与代码有关,因为它仅适用于英文单词。

谢谢!

该计划包括3个课程。

package chap14;
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;

public class QuizCardReader {

private JTextArea display;
private JTextArea answer;
private ArrayList cardList;
private QuizCard currentCard;
private Iterator cardIterator;
private JFrame frame;
private JButton nextButton;
private boolean isShowAnswer;


public static void main (String[] args) {
   QuizCardReader qReader = new QuizCardReader();
   qReader.go();
}

public void go() {

    frame = new JFrame("Quiz Card Player");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel mainPanel = new JPanel();
    Font bigFont = new Font("sanserif", Font.BOLD, 24);

    display = new JTextArea(9,20);
    display.setFont(bigFont);
    display.setLineWrap(true);
    display.setWrapStyleWord(true);
    display.setEditable(false);

    JScrollPane qScroller = new JScrollPane(display);
    qScroller.setVerticalScrollBarPolicy(
          ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    qScroller.setHorizontalScrollBarPolicy(
          ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

    nextButton = new JButton("Show Question");

    mainPanel.add(qScroller);
    mainPanel.add(nextButton);
    nextButton.addActionListener(new NextCardListener());
    JMenuBar menuBar = new JMenuBar();
    JMenu fileMenu = new JMenu("File");

    JMenuItem loadMenuItem = new JMenuItem("Load card set");

    loadMenuItem.addActionListener(new OpenMenuListener());

    fileMenu.add(loadMenuItem);

    menuBar.add(fileMenu);
    frame.setJMenuBar(menuBar);

    frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
    frame.setSize(500,600);
    frame.setVisible(true);        
  }


  public class NextCardListener implements ActionListener {
    public void actionPerformed(ActionEvent ev) {
      if (isShowAnswer) {

         display.setText(currentCard.getAnswer());
         nextButton.setText("Next Card");
         isShowAnswer = false;
      } else {

         if (cardIterator.hasNext()) {

            showNextCard();

          } else {

             display.setText("That was last card");
             nextButton.disable();
          }
       }
    }
   }


  public class OpenMenuListener implements ActionListener {
    public void actionPerformed(ActionEvent ev) {
         JFileChooser fileOpen = new JFileChooser();
         fileOpen.showOpenDialog(frame);
         loadFile(fileOpen.getSelectedFile());
    }
  }

  private void loadFile(File file) {
  cardList = new ArrayList();
  try {
     BufferedReader reader = new BufferedReader(new FileReader(file));
     String line = null;
     while ((line = reader.readLine()) != null) {
        makeCard(line);
     }
     reader.close();

  } catch(Exception ex) {
      System.out.println("couldn't read the card file");
      ex.printStackTrace();
  }


 cardIterator = cardList.iterator();
 showNextCard();
}

 private void makeCard(String lineToParse) {

  StringTokenizer parser = new StringTokenizer(lineToParse, "/");
  if (parser.hasMoreTokens()) {
     QuizCard card = new QuizCard(parser.nextToken(), parser.nextToken());
     cardList.add(card);
  }
}

 private void showNextCard() {
    currentCard = (QuizCard) cardIterator.next();
    display.setText(currentCard.getQuestion());
    nextButton.setText("Show Answer");
    isShowAnswer = true;
 }
 }

这是第二堂课。

package chap14;
import java.io.*;

public class QuizCard implements Serializable {

 private String uniqueID;
 private String category;
 private String question;
 private String answer;
 private String hint;

 public QuizCard(String q, String a) {
     question = q;
     answer = a;
}


 public void setUniqueID(String id) {
    uniqueID = id;
 }

 public String getUniqueID() {
    return uniqueID;
 }

 public void setCategory(String c) {
    category = c;
 }

 public String getCategory() {
     return category;
 }

 public void setQuestion(String q) {
    question = q;
 }

 public String getQuestion() {
    return question;
 }

 public void setAnswer(String a) {
    answer = a;
 }

 public String getAnswer() {
    return answer;
 }

 public void setHint(String h) {
    hint = h;
 }

 public String getHint() {
    return hint;
 }

}

第三等

package chap14;
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;

public class QuizCardBuilder {

private JTextArea question;
private JTextArea answer;
private ArrayList cardList;
private JFrame frame;



public static void main (String[] args) {
   QuizCardBuilder builder = new QuizCardBuilder();
   builder.go();
}

public void go() {

    frame = new JFrame("Quiz Card Builder");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  // title bar
    JPanel mainPanel = new JPanel();
    Font bigFont = new Font("sanserif", Font.BOLD, 24);
    question = new JTextArea(6,20);
    question.setLineWrap(true);
    question.setWrapStyleWord(true);
    question.setFont(bigFont);

    JScrollPane qScroller = new JScrollPane(question);
    qScroller.setVerticalScrollBarPolicy(
              ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    qScroller.setHorizontalScrollBarPolicy(
              ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

    answer = new JTextArea(6,20);
    answer.setLineWrap(true);
    answer.setWrapStyleWord(true);
    answer.setFont(bigFont);

    JScrollPane aScroller = new JScrollPane(answer);
    aScroller.setVerticalScrollBarPolicy(
              ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    aScroller.setHorizontalScrollBarPolicy(
              ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

    JButton nextButton = new JButton("Next Card");
    cardList = new ArrayList();
    JLabel qLabel = new JLabel("Question:");
    JLabel aLabel = new JLabel("Answer:");

    mainPanel.add(qLabel);
    mainPanel.add(qScroller);
    mainPanel.add(aLabel);
    mainPanel.add(aScroller);
    mainPanel.add(nextButton);
    nextButton.addActionListener(new NextCardListener());
    JMenuBar menuBar = new JMenuBar();
    JMenu fileMenu = new JMenu("File");
    JMenuItem newMenuItem = new JMenuItem("New");

    JMenuItem saveMenuItem = new JMenuItem("Save");
    newMenuItem.addActionListener(new NewMenuListener());
    saveMenuItem.addActionListener(new SaveMenuListener());

    fileMenu.add(newMenuItem);
    fileMenu.add(saveMenuItem);
    menuBar.add(fileMenu);
    frame.setJMenuBar(menuBar);

    frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
    frame.setSize(500,600);
    frame.setVisible(true);        
 }


 public class NextCardListener implements ActionListener {
   public void actionPerformed(ActionEvent ev) {
      QuizCard card = new QuizCard(question.getText(), answer.getText());
      cardList.add(card);
      clearCard();

    }
 }

 public class SaveMenuListener implements ActionListener {
    public void actionPerformed(ActionEvent ev) {
       QuizCard card = new QuizCard(question.getText(), answer.getText());
       cardList.add(card);

       JFileChooser fileSave = new JFileChooser();
       fileSave.showSaveDialog(frame);
       saveFile(fileSave.getSelectedFile());
     }
  }

  public class NewMenuListener implements ActionListener {
    public void actionPerformed(ActionEvent ev) {
       cardList.clear();
       clearCard();           
     }
  }


  private void clearCard() {
     question.setText("");
     answer.setText("");
     question.requestFocus();
  }

  private void saveFile(File file) {

   try {
      BufferedWriter writer = new BufferedWriter(new FileWriter(file));
      Iterator cardIterator = cardList.iterator();
      while (cardIterator.hasNext()) {
         QuizCard card = (QuizCard) cardIterator.next();
         writer.write(card.getQuestion() + "/");
         writer.write(card.getAnswer() + "\n");
      }
     writer.close();


   } catch(IOException ex) {
       System.out.println("couldn't write the cardList out");
       ex.printStackTrace();
      }
   }
}

当我尝试使程序从文本文件中读取日语时遇到的错误:

couldn't read the card file
java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(Unknown Source)
at chap14.QuizCardReader.makeCard(QuizCardReader.java:122)
at chap14.QuizCardReader.loadFile(QuizCardReader.java:104)
at chap14.QuizCardReader.access$8(QuizCardReader.java:98)
at chap14.QuizCardReader$OpenMenuListener.actionPerformed(QuizCardReader.java:94)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.AbstractButton.doClick(Unknown Source)
at javax.swing.plaf.basic.BasicMenuItemUI.doClick(Unknown Source)
at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

问题答案:
 BufferedReader reader = new BufferedReader(new FileReader(file));

应该

 BufferedReader reader = new BufferedReader(new InputStreamReader(
     new FileInputStream(file), StandardCharsets.UTF_8));

FileReader是一个旧的实用程序类,没有设置编码的选项。那绊倒了你。对于FileWriter来说也是如此,应该使用带有FileOutputStream和编码的OutputStreamWriter。

这是否对扫描仪有帮助,还有待观察。

StringTokenizer parser = new StringTokenizer(lineToParse, "/");
if (parser.hasMoreTokens()) {
    String q = parser.nextToken();
    if (parser.hasMoreTokens()) {
        String a = parser.nextToken();
        QuizCard card = new QuizCard(q, a);
        cardList.add(card);
    }
}

要么

String[] qa = lineToParse.split("/", 2);
if (qa.length == 2) {
    QuizCard card = new QuizCard(qa[0], aq[1]);
    cardList.add(card);
}

后者会{"Kiom", "3 / 4"}由于的原因将“ Kiom?/ 3/4”拆分为两个split(-, 2)



 类似资料:
  • 问题内容: 真正简单的问题。我需要在Java程序中读取Unicode文本文件。 我习惯于使用带有BufferedReader FileReader组合的纯ASCII文本,这显然不起作用:( 我知道我可以使用“缓冲读取器”以“传统”方式读取字符串,然后使用类似以下方式的字符串进行转换: 但是,有没有办法将阅读器包装在“转换器”中? 编辑:文件以FF FE开头 问题答案: 您不会包装Reader,而是

  • 问题内容: 如何从Java中classpath读取文本文件? 问题答案: 在类路径上的目录中,从同一类加载器加载的类中,你应该能够使用以下任一种: 如果这些都不起作用,则表明还有其他问题。 因此,例如,使用以下代码: 而这个目录结构: 然后(使用Linux机器上的Unix路径分隔符): 结果:

  • 问题内容: 我想读取一个包含空格分隔值的文本文件。值是整数。如何读取并将其放入数组列表? 这是文本文件内容的示例: 我想将它包含在arraylist中。如何用Java做到这一点? 问题答案: 你可以用来将文本文件的所有行都放入。 教程:基本文件读取,写入和创建文本文件 你可以用来基于正则表达式拆分部分。 教程:数字和字符串>字符串>操纵字符串中的字符 你可以使用将转换为。 教程:数字和字符串>字符

  • 问题内容: 我可以从文件中读取内容,并且能够通过更改for循环中的数字来更改行数,但是我不希望那样并排显示文件中的所有数字。我需要它们全部一一随机掉下来。 问题答案: 我想你要打印的是 仅显示此列表(可能包含100条)中的前20条随机行

  • 我的项目中有这样一段代码: 没有错误,应用程序运行正常,但是变量中从来没有任何文本,我确信txt文件中有文本! 我已经尝试过不同的方法来读取文本文件(使用BufferedReader、Scanner、FileInputStream和FileReader),但都不起作用。 另外,我几乎可以肯定问题不在变量中,因为我尝试通过代码(使用运行时)打开文件,它正常打开了正确的文件。 好的,我尝试添加,但是仍

  • 问题内容: 我需要在存储过程中读入由SSIS包创建的日志文件。 有什么好方法吗? 我尝试使用此代码,但将文件内容显示为乱码。有没有解决的编码问题?有没有更简单的方法? 问题答案: 您是否尝试过将笔直插入?例如: