我已经创建了一个AWT框架,它接受文本区域中的文本输入,可以计数单词和字符的数量,或者它可以将其内容保存到"trial.txt“文件中。
这是供参考的全部代码:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class trial extends Frame
{
static TextArea ta=new TextArea("Welcome");
static Label l1=new Label("Words:");
static Label l2=new Label("Characters:");
static Button b=new Button("Count");
static Button save=new Button("Save");
static BufferedOutputStream bos;
trial()
{
//Setting position
ta.setBounds(300,300,300,300);
l1.setBounds(50,50,100,100);
l2.setBounds(50,200,100,100);
b.setBounds(650,300,50,50);
save.setBounds(650,400,50,50);
//Setting up file for saving
try {
bos=new BufferedOutputStream(new FileOutputStream("C:\\trial.txt"));
} catch (Exception e) {
e.printStackTrace();
}
save.addActionListener(new Save());
//Adding the components
this.add(ta);
this.add(l1);
this.add(l2);
this.add(b);
this.add(save);
//adding actionlistener to button
b.addActionListener(new actionlistener());
//setting up frame
this.setSize(1000,1000);
this.setLayout(null);
this.setVisible(true);
}
public static class actionlistener implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
String text=ta.getText();
String words[]=text.split("\\s");
l1.setText("Words:"+words.length);
l2.setText("Characters:"+text.length());
}
}
public static class Save implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
String text=ta.getText();
byte[] arr=text.getBytes();
try
{
bos.write(arr);
} catch (IOException f)
{
}
}
}
public static void main(String args[])
{
trial ttt=new trial();
}
}我已经复制了正确的路径,这是在上面给出的代码。我还允许java读写。但是代码显示了java.io.FileNotFoundException: C:\trial.txt (Access is denied)。
发布于 2022-05-24 07:19:24
哦,这很容易,只是一个愚蠢的错误。需要将文件名作为参数而不是文件路径。它现在没有显示错误,但是它没有将文件的内容保存到txt文件中。
*编辑:这是工作的now.Thank你们大家为你的帮助。
https://stackoverflow.com/questions/72357279
复制相似问题