永发信息网

关于java FileOutputStream和FileInputStream的小问题

答案:1  悬赏:70  手机版
解决时间 2021-04-28 02:45
  • 提问者网友:听门外雪花风
  • 2021-04-27 13:54

有这样一个题:

编写应用程序,界面如图8.8所示。当用户在第一个文本框内填入文件的路径后单击“打开文件”按钮,文件的内容显示在下面的文本区域内,在文本区域内对文件做出修改后,单击“存储文件”按钮,则可以将文件存入原来的文件名中。

我编写的程序是这样的:

//程序文件名为CeShiFile.java
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import java.io.*;
public class CeShiFile extends JFrame implements ActionListener
{
 JLabel jlbName = new JLabel("文件名");
 JTextField tfName = new JTextField(20);
 JButton btnOpen = new JButton("打开文件");
 JButton btnSave = new JButton("存储文件");
 JTextArea taText = new JTextArea(5,20);
 JPanel p1 = new JPanel();
 JPanel p2 = new JPanel();
 JPanel p3 = new JPanel();
 JPanel p4 = new JPanel(new BorderLayout());
 JPanel p5 = new JPanel(new BorderLayout());
 public CeShiFile()
 {
   p1.add(jlbName);
   p2.add(tfName);
   p3.add(btnOpen);
   p3.add(btnSave);
   JScrollPane s = new JScrollPane(taText);
   p4.add(p1,BorderLayout.NORTH);
   p4.add(p2,BorderLayout.CENTER);
   p4.add(p3,BorderLayout.SOUTH);
   p5.add(p4,BorderLayout.NORTH);
   p5.add(s,BorderLayout.CENTER);
   getContentPane().add(p5,BorderLayout.CENTER);
   btnOpen.addActionListener(this);
   btnSave.addActionListener(this);
  }
  public void actionPerformed(ActionEvent a)
  {
   try
   {
     String arg = a.getActionCommand();
      String str = tfName.getText();
      byte buf[] = new byte[2056];
      byte bufIn[] = new byte[2056];
      int bytes;
     if(arg == "打开文件")
     {
      FileInputStream fileIn = new FileInputStream(str);
      bytes = fileIn.read(buf,0,2056);
      String strin = new String(buf,0,bytes);
      taText.setText(strin);
     }
     else if(arg == "存储文件")
     {
      String str1 = taText.getText();
      buf = str1.getBytes();
      FileOutputStream fileOut = new FileOutputStream(str);
      fileOut.write(buf,0,buf.length);
      fileOut.flush();
      fileOut.close();
      bytes = System.in.read(bufIn,0,2056);
      fileOut = new FileOutputStream(str,true);
      fileOut.write(bufIn,0,bytes);
     }
    }
    catch(IOException e)
    {
     System.out.println(e.getMessage());
    }
  }
  public static void main(String args[])
  {
   CeShiFile CS = new CeShiFile();
   CS.setSize(300,300);
   CS.show();
  }
}

 

经过测试程序可以执行,题中要求也能完成。但有一个小问题,就是在点击了“存储文件”后虽然能将修改过的内容进行保存,但程序会卡住不响应,只能在命令行强行关闭。请问谁能告诉我这是什么原因?

最佳答案
  • 五星知识达人网友:空山清雨
  • 2021-04-27 15:22

把这3句话去掉就可以了


bytes = System.in.read(bufIn,0,2056);
      fileOut = new FileOutputStream(str,true);
      fileOut.write(bufIn,0,bytes);

我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯