this is in java 1. Selects a text file from your computer using a Java Swing JFi
ID: 2246563 • Letter: T
Question
this is in java
1. Selects a text file from your computer using a Java Swing JFileChooser or a JavaFX FileChooser, which starts out showing the files in the same directory from which the program was executed.
2. Reads the selected text file. The text file for my test will consist of a number of rows, each row containing one or more strings of characters, separated by spaces. The strings themselves will only contain printable, non-space characters.
3. Writes the final string of each input line to a separate line on the output file. The output text file will be in the same directory as the input text file, where the naming convention is as follows: If the input file is abc.txt, the output file is abc_out.txt.
Explanation / Answer
Here is your code for JFileChooser.
import javax.swing.*;
import javax.swing.fileChooser;
import java.awt.event.*;
import java.io.*;
class MyFrame extends JFrame implements ActionListener
{
JLabel l1,l2,l3;
JTextBox t1,t2;
JButton b1;
JPanel p1;
public MyFrame(String s)
{
super(s);
setSize(400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p1=new JPanel();
l1=new JLabel("Select input file name");
l2=new JLabel("Input File");
l3=new JLabel("Output File");
t1=new JTextBox(30);
t2=new JTextBox(30);
b1=new JButton("Click");
p1.add(l1);
p1.add(b1);
p1.add(l2);
p1.add(t1);
p1.add(l3);
p1.add(t2);
add(p1);
b1.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
JFileChooser f=new JFileChooser();
int r=f.showOpenDialog(null);
File f1=f.getSelectedFile();
if(r==JFileChooser.APPROVE_OPTION)
String n=f1.getName();
t1.setText(n);
FileInputStream fin=null;
FileOutputStream fout=null;
try
{
fin=new FileInputStream(n);
}
catch(FileNotFoundException e1){ }
try
{
fout=new FileOutPutStream(t2.getText());
}
catch(FileNotFoundException e2){ }
//read fin,write fout
int x=0;
while((x=fin.read())!=-1)
fout.write(x);
fin.close();
fout.close();
}
}
class FileDemo
{
public static void main(String args[])
{
new MyFrame("File Chooser");
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.