I am writing a program that "deletes" a line in a text file. How ever It is failing to both delete the original file and rename the new file.
What happens is, it will save the lines I want to save under the file name "temp.txt". However What it should do is delete the original file(TaskList.txt) and then rename temp.txt as TaskList.txt can anyone help? Here is my code:
import java.io.*;
import java.io.File;
import java.awt.*;
import javax.swing.*;
import java.util.Scanner;
import java.awt.event.*;
class DeleteTask implements ActionListener{
private static Scanner x;
JFrame frame;
JButton deleteButton;
JTextField delete;
JLabel label;
public void completedTask()
{
frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.setTitle("Delete Task");
delete = new JTextField(10);
deleteButton = new JButton("Delete");
deleteButton.addActionListener(this);
label = new JLabel ("Enter task name");
frame.add(label,BorderLayout.WEST);
frame.add(delete,BorderLayout.CENTER);
frame.add(deleteButton,BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event)
{
String filePath = "TaskList.txt";
String removeTerm= delete.getText();
removeRecord(filePath,removeTerm);
frame.dispose();
}
public static void removeRecord(String filePath, String removeTerm)
{
String tempFile = "temp.txt";
File oldFile = new File(filePath);
File newFile = new File(tempFile);
String id = "" ; String name = "" ; String age = ""; String descript = "";
try
{
FileWriter fw = new FileWriter(tempFile,true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
x = new Scanner(new File(filePath));
x.useDelimiter("[,\n]");
while(x.hasNext())
{
id = x.next();
name = x.next();
age = x.next();
descript = x.next();
if(!id.equals(removeTerm))
{
pw.println(id + ", " + name + ", " + age + ", " + descript);
}
}
x.close();
pw.flush();
pw.close();
oldFile.delete();
File dump = new File(filePath);
newFile.renameTo(dump);
}
catch(Exception E)
{
}
}
}
Related
I'm having a problem with my methods for a school assignment which are supposed to load and save String arrays to a file. It seems like it does not save or load properly. For example, I saved a string of "ok" in a file, let's call it x. Then I rerun the app and changed the path to a directory and it read the string "ok" from it even though it wasn't initially saved the directory and the directory shouldn't be allowed anyways. I really don't know how to solve it and I tried to manipulate the code but I do not know what causes it so it's hard to think of a solution.
Some details on my task:
have to use File Output/Input Stream and Object Output/Input Stream
question and answer strings have to be initialized to 0 size if the path is empty/is a dir/ file not found
take answer and question string from textfield, save it to a file and read the existing ones from the file
question and answer string arrays have to be in a separate class
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.Arrays;
public class App2 extends JFrame implements ActionListener {
JPanel mpanel, qpanel, apanel, bpanel, upanel;
JTextField tf1, tf2, tf3;
JButton jb;
JLabel jl1, jl2, jl3;
String path;
public static void main(String[] args) {
App2 object = new App2();
System.out.println("app init/ array size:" + QAData.question.length);
}
App2() {
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(400, 200);
this.setTitle("App2");
mpanel = new JPanel();
this.add(mpanel);
mpanel.setLayout(new GridLayout(4, 1));
qpanel = new JPanel();
mpanel.add(qpanel);
apanel = new JPanel();
mpanel.add(apanel);
upanel = new JPanel();
mpanel.add(upanel);
bpanel = new JPanel();
mpanel.add(bpanel);
jl1 = new JLabel("Question: ");
qpanel.add(jl1);
tf1 = new JTextField(20);
tf1.setHorizontalAlignment(JTextField.LEFT);
qpanel.add(tf1);
tf1.addActionListener(this);
jl2 = new JLabel("Answer: ");
apanel.add(jl2);
tf2 = new JTextField(20);
tf2.setHorizontalAlignment(JTextField.LEFT);
apanel.add(tf2);
tf2.addActionListener(this);
jl3 = new JLabel("Path: ");
upanel.add(jl3);
tf3 = new JTextField(20);
tf3.setHorizontalAlignment(JTextField.LEFT);
upanel.add(tf3);
tf3.addActionListener(this);
jb = new JButton("Update");
jb.setHorizontalAlignment(JButton.CENTER);
bpanel.add(jb);
jb.addActionListener(this);
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == tf3)
path = tf3.getText();
if (e.getSource() == jb) {
load();
save();
tf1.setText("");
tf2.setText("");
}
}
void load() {
try {
File file = new File("path");
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
boolean fileIsOk = file.isFile() && !(tf3.getText().equals("")) && !(file.isDirectory());
if (!fileIsOk) {
QAData.question = new String[0];
QAData.answer = new String[0];
System.out.println("size 0 applied");
} else {
QAData.question = (String[]) ois.readObject();
QAData.answer = (String[]) ois.readObject();
}
ois.close();
} catch (ClassNotFoundException e) {
System.out.println("No such class found");
e.printStackTrace();
} catch (IOException e) {
System.out.println("I/O exception during the load");
e.printStackTrace();
} catch (NullPointerException e) {
System.out.println("The object you are trying to read has the null value");
e.printStackTrace();
}
}
void save() {
try {
File file = new File("path");
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
boolean fileIsOk = file.isFile() && !(tf3.getText().equals("")) && !(file.isDirectory());
if (fileIsOk) {
QAData.question = Arrays.copyOf(QAData.question, QAData.question.length + 1);
QAData.question[(QAData.question.length - 1)] = tf1.getText();
QAData.answer = Arrays.copyOf(QAData.answer, QAData.answer.length + 1);
QAData.answer[(QAData.answer.length - 1)] = tf2.getText();
oos.writeObject(QAData.question);
oos.writeObject(QAData.answer);
}
oos.close();
} catch (IOException e) {
System.out.println("I/O exception during the save");
e.printStackTrace();
} catch (NullPointerException e) {
System.out.println("The object you are trying to save has the null value");
e.printStackTrace();
}
}
static class QAData implements Serializable {
static String[] question = new String[0];
static String[] answer = new String[0];
}
}
I have this app that runs in eclipse's console and I want it to run in a jframe.
By that I mean that I want it to ask for name, a and b on the JFrame window and then write something on a file.
It works perfectly in the console but I don't know how to run it as a JFrame.
I want it to look something like this(Image made in photoshop):
http://i.imgur.com/rTWko1R.png
And then automaticaly close
Thanks in advance!
some imports...(trying to save space)
public class Test {
public static void main(String[] args) throws FileNotFoundException,IOException {
Scanner s = new Scanner(System.in);
String fileName = new SimpleDateFormat("dd-MM-yyyy_HH-mm'.txt'").format(new Date());
String obs;
String name;
String path = "some path";
int a = 0, b = 0, c = 0, d = 0;
System.out.println("input file name");
name = s.nextLine();
System.out.println("input a");
a = s.nextInt();
System.out.println("input b");
b = s.nextInt();
obs = s.nextLine();
if (a >= 100) {
d = a / 100;
c = a % 100;
b = c;
a = a + d;
}
File file;
if (StringUtils.isBlank(name)) {
file = new File(path + fileName);
} else {
file = new File(path + name + "#" + fileName);
}
FileWriter writer = null;
try {
writer = new FileWriter(file);
writer.write("something");
if (StringUtils.isBlank(obs)) {
writer.write("something");
} else {
writer.write(obs + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null)
try {
writer.close();
} catch (IOException ignore) {
}
}
}
}
What you'll need to do
separate out your core logic into a separate method that takes String name, int a, int b, ideally in a separate class - then you can reuse from your console version
Create a basic GUI in a frame with a button to kick off the process
listen to the button press and call core logic method
add validation of inputs if necessary
consider using JFileChooser to allow user to pick the file rather than having to type it in
Example
public class ConsoleInFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new ConsoleInFrame().showGui();
}
});
}
public void showGui() {
JFrame frame = new JFrame();
JTextField file = new JTextField(20);
JTextField aText = new JTextField(4);
JTextField bText = new JTextField(4);
JButton go = new JButton("Go");
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 2));
panel.add(new JLabel("File"));
panel.add(file);
panel.add(new JLabel("a"));
panel.add(aText);
panel.add(new JLabel("b"));
panel.add(bText);
frame.getContentPane().setLayout(
new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
frame.getContentPane().add(panel);
frame.getContentPane().add(go);
go.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
process(file.getText(), Integer.parseInt(aText.getText()),
Integer.parseInt(bText.getText()));
}
});
frame.pack();
frame.setVisible(true);
}
public void process(String name, int a, int b) {
String fileName = new SimpleDateFormat("dd-MM-yyyy_HH-mm'.txt'")
.format(new Date());
String obs;
String path = "some path";
int c = 0, d = 0;
if (a >= 100) {
d = a / 100;
c = a % 100;
b = c;
a = a + d;
}
File file;
if (StringUtils.isBlank(name)) {
file = new File(path + fileName);
} else {
file = new File(path + name + "#" + fileName);
}
FileWriter writer = null;
try {
writer = new FileWriter(file);
writer.write("something");
if (StringUtils.isBlank(obs)) {
writer.write("something");
} else {
writer.write(obs + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null)
try {
writer.close();
} catch (IOException ignore) {
}
}
}
}
I think you could do something like this:
To do this you have to use JLabel to display text: https://docs.oracle.com/javase/tutorial/uiswing/components/label.html
Then to get the input use JTextField:
https://docs.oracle.com/javase/tutorial/uiswing/components/textfield.html
And if you want you can use a JButton after you write in the JTextField to save everything to the file:
https://docs.oracle.com/javase/7/docs/api/javax/swing/JButton.html
http://www.javamex.com/tutorials/swing/jbutton.shtml
My program right now needs to load up two text files and I'm sorting them by string of words. JcomboxBox is supposed to allow you to select int between 1 and 4 (the size of the string to compare)
so 2 would return "I am" whereas 1 would return "I"
I'm getting null pointed exception and I have never used combo boxes before. Please help/
import java.awt.GridLayout;
import javax.swing.JFrame;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.Scanner;
import java.util.Arrays;
import javax.swing.JComboBox;
public class Lab8 extends JPanel
{
private JPanel text;
private JComboBox input;
private JLabel label;
private JButton load, go,go2;
private CountList<SuperString> words;
private String filename;
private int width = 400;
private int height = 600;
private TextArea textarea,textarea2;
Scanner scan;
public Lab8()
{
Integer [] select = {1,2,3,4};
JComboBox input = new JComboBox(select);
text = new JPanel(new GridLayout(1,2));
go = new JButton("Select Text File");
go2 = new JButton("Select 2nd Text File");
label = new JLabel("How many sequenced words would you like to analyze? (Must be => 1)" );
input.setSelectedIndex(0);
ButtonListener listener = new ButtonListener();
go.addActionListener(listener);
go2.addActionListener(listener);
input.addActionListener(listener);
textarea = new TextArea("",0,0,TextArea.SCROLLBARS_VERTICAL_ONLY);
textarea2 = new TextArea("",0,0,TextArea.SCROLLBARS_VERTICAL_ONLY);
textarea.setFont(new Font("Helvetica",Font.PLAIN,24));
textarea2.setFont(new Font("Helvetica",Font.PLAIN,24));
textarea.setPreferredSize(new Dimension(width,height));
textarea2.setPreferredSize(new Dimension(width,height));
setPreferredSize(new Dimension(900,600));
text.add(textarea);
text.add(textarea2);
add(input);
add(go);
add(go2);
add(text);
textarea.setText("No File Selected");
textarea2.setText("No File Selected");
}
public class ButtonListener implements ActionListener //makes buttons do things
{
JFileChooser chooser = new JFileChooser("../Text");
public void actionPerformed(ActionEvent event)
{
Integer N = input.getSelectedIndex();
if(event.getSource() == go)
{
int returnvalue = chooser.showOpenDialog(null);
if(returnvalue == JFileChooser.APPROVE_OPTION)
{
try
{
File file = chooser.getSelectedFile();
filename = file.getName();
System.err.println(filename);
scan = new Scanner(file);
}
catch (IOException e)
{
System.err.println("IO EXCEPTION");
return;
}
}
else
{
return;
}
String[] storage = new String[N];
words = new CountLinkedList<SuperString>();
for(int i=1;i<N;i++)
storage[i] = scan.next().toLowerCase().replace(",","").replace(".","");
while(scan.hasNext())
{
for(int i=0;i<=N-2;i++)
storage[i] = storage[i+1];
storage[N-1] = scan.next().toLowerCase();
storage[N-1] = storage[N-1].replace(",","").replace(".","");
SuperString ss = new SuperString(storage);
// System.out.println(ss);
words.add(ss );
}
scan.close();
textarea.append(" "+filename+" has wordcount: "+words.size()+
"\n-------------------------\n\n");
SuperString[] ss = new SuperString[words.size()];
int i=0;
for(SuperString word: words)
{
ss[i] = word;
i++;
}
Arrays.sort(ss, new SuperStringCountOrder());
for(SuperString word : ss)
{
textarea.append(" "+word+"\n");
}
}
if(event.getSource() == go2)
{
int returnvalue = chooser.showOpenDialog(null);
if(returnvalue == JFileChooser.APPROVE_OPTION)
{
try
{
File file = chooser.getSelectedFile();
filename = file.getName();
System.err.println(filename);
scan = new Scanner(file);
}
catch (IOException e)
{
System.err.println("IO EXCEPTION");
return;
}
}
else
{
return;
}
String[] storage = new String[N];
words = new CountLinkedList<SuperString>();
for(int i=1;i<N;i++)
storage[i] = scan.next().toLowerCase().replace(",","").replace(".","");
while(scan.hasNext())
{
for(int i=0;i<=N-2;i++)
storage[i] = storage[i+1];
storage[N-1] = scan.next().toLowerCase();
storage[N-1] = storage[N-1].replace(",","").replace(".","");
SuperString ss = new SuperString(storage);
words.add(ss );
}
scan.close();
textarea2.append(" "+filename+" has wordcount: "+words.size()+
"\n-------------------------\n\n");
SuperString[] ss = new SuperString[words.size()];
int i=0;
for(SuperString word: words)
{
ss[i] = word;
i++;
}
Arrays.sort(ss, new SuperStringCountOrder());
for(SuperString word : ss)
{
textarea2.append(" "+word+"\n");
}
}
}
}
public static void main(String[] arg)
{
JFrame frame = new JFrame("Lab 8");
frame.getContentPane().add(new Lab8());
frame.pack();
frame.setVisible(true);
}
}
You're re-declaring your JComboBox variable in the constructor and thus shadowing the field found in the class. By doing this the field remains null:
public class Lab8 extends JPanel
{
private JPanel text;
private JComboBox input; // this guy remains null
// .... etc ....
public Lab8()
{
Integer [] select = {1,2,3,4};
// the line below initializes a local input variable.
// this variable is visible only inside of the constructor
JComboBox input = new JComboBox(select); // ***** here ****
Don't re-declare the variable:
public class Lab8 extends JPanel
{
private JPanel text;
private JComboBox input;
// .... etc ....
public Lab8()
{
Integer [] select = {1,2,3,4};
// JComboBox input = new JComboBox(select); // ***** here ****
input = new JComboBox(select); // ***** note difference? *****
here is my application. I'm having a problem saving objects and opening them. When I try to save it tells me the variable in the save.writeObject(firstName) cannot be resolved to a variable.
The problem is in the ActionPeformed block:
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
import java.util.*;
public class ClassRoomFrameTest
{
public static void main(String[] args)
{
ClassRoomFrame frame = new ClassRoomFrame();
frame.setSize(600,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
}
}
class ClassRoomFrame extends JFrame implements ActionListener
{
private JPanel mainPanel = new JPanel();
private JPanel deptPanel = new JPanel(new GridLayout(2,3));
private JPanel studentPanel = new JPanel(new GridLayout(2,5));
private JPanel displayPanel = new JPanel(new BorderLayout());
private JPanel buttonPanel = new JPanel(new GridLayout(1,2));
private JPanel menuBar = new JPanel();
private JTextArea textArea = new JTextArea();
private JScrollPane scrollPane = new JScrollPane(textArea);
private JLabel classLocationLabel = new JLabel("Class Location");
private JLabel classRoomLabel = new JLabel("Class Room Number");
private JLabel classCapacityLabel = new JLabel("Class Capacity");
private JTextField classLocationField = new JTextField();
private JTextField classRoomField = new JTextField();
private JTextField classCapacityField = new JTextField();
private JLabel studentFNameLabel = new JLabel("First name");
private JLabel studentLNameLabel = new JLabel("Last name");
private JLabel studentIDLabel = new JLabel("ID Number");
private JLabel studentMajorLabel = new JLabel("Major");
private JLabel studentCreditsLabel = new JLabel("Credits");
private JTextField studentFNameField = new JTextField();
private JTextField studentLNameField = new JTextField();
private JTextField studentIDField = new JTextField();
private JTextField studentMajorField = new JTextField();
private JTextField studentCreditsField = new JTextField();
private JButton addButton = new JButton("Add");
private JButton displayButton = new JButton("Display");
private JMenuBar menu = new JMenuBar();
private JMenu fileMenu = new JMenu("File");
private JMenuItem save = new JMenuItem("Open");
private JMenuItem open = new JMenuItem("Save");
private JFileChooser chooser = new JFileChooser();
Classroom room = null;
public ClassRoomFrame()
{
deptPanel.setPreferredSize(new Dimension(600,50));
deptPanel.setBorder(new EmptyBorder(new Insets(5,15,5,15)));
deptPanel.add(classLocationLabel);
deptPanel.add(classRoomLabel);
deptPanel.add(classCapacityLabel);
deptPanel.add(classLocationField);
deptPanel.add(classRoomField);
deptPanel.add(classCapacityField);
fileMenu.add(fileMenu);
fileMenu.add(open);
fileMenu.add(save);
menu.add(fileMenu);
studentPanel.setBorder(new EmptyBorder(new Insets(5,15,5,15)));
studentPanel.setPreferredSize(new Dimension(600,50));
studentPanel.setBorder(new EmptyBorder(new Insets(5,15,5,15)));
studentPanel.add(studentFNameLabel);
studentPanel.add(studentLNameLabel);
studentPanel.add(studentIDLabel);
studentPanel.add(studentMajorLabel);
studentPanel.add(studentCreditsLabel);
studentPanel.add(studentFNameField);
studentPanel.add(studentLNameField);
studentPanel.add(studentIDField);
studentPanel.add(studentMajorField);
studentPanel.add(studentCreditsField);
scrollPane.setBorder(new BevelBorder(BevelBorder.LOWERED));
scrollPane.setPreferredSize(new Dimension(600,450));
textArea.setBorder(new EmptyBorder(new Insets(5,15,5,15)));
buttonPanel.setBorder(new BevelBorder(BevelBorder.RAISED));
buttonPanel.setPreferredSize(new Dimension(600, 50));
buttonPanel.add(addButton);
buttonPanel.add(displayButton);
addButton.addActionListener(this);
addButton.setActionCommand("Add");
displayButton.addActionListener(this);
displayButton.setActionCommand("Display");
open.addActionListener(this);
open.setActionCommand("Open");
save.addActionListener(this);
save.setActionCommand("Save");
mainPanel.add(deptPanel);
mainPanel.add(studentPanel);
mainPanel.add(scrollPane);
add(menu, BorderLayout.NORTH);
add(mainPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
}
#SuppressWarnings("unused")
public void actionPerformed(ActionEvent e)
{
/*---> HERE */if(e.getActionCommand().equals("Save"));
{
FileOutputStream saveFile = null;
ObjectOutputStream save = null;
try
{
saveFile = new FileOutputStream("ObjectData.txt");
save = new ObjectOutputStream(saveFile);
/*--->Error*/ save.writeObject(index);
save.writeObject(new Classroom());
} catch (FileNotFoundException e1)
{
e1.printStackTrace();
} catch (IOException e1)
{
e1.printStackTrace();
}
finally
{
try {saveFile.close();
}catch(Exception exc){
System.out.println(exc.getMessage());
}
}
}
/*---> Here*/if (e.getActionCommand().equals("Open"))
{
ObjectInputStream in = null;
int returnVal = chooser.showOpenDialog(ClassRoomFrame.this);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File file = chooser.getSelectedFile();
try {
in = new ObjectInputStream(new FileInputStream(file));
} catch (FileNotFoundException e1)
{
e1.printStackTrace();
} catch (IOException e1)
{
e1.printStackTrace();
}
}
try {
Student st = (Student)in.readObject();
Classroom cs = (Classroom)in.readObject();
System.out.println(st);
System.out.println(cs);
} catch (IOException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
try{in.close();}
catch(Exception err){err.getMessage();}
}
if(e.getActionCommand().equals("Add"))
{
if(room == null)
{
room = new Classroom(classLocationField.getText(),
Integer.parseInt(classRoomField.getText()),
Integer.parseInt(classCapacityField.getText()));
room.addStudent(
new Student(studentFNameField.getText(),
studentLNameField.getText(),
studentIDField.getText(),
studentMajorField.getText(),
Integer.parseInt(studentCreditsField.getText())));
classLocationField.setEditable(false);
classRoomField.setEditable(false);
classCapacityField.setEditable(false);
studentFNameField.setText("");
studentLNameField.setText("");
studentIDField.setText("");
studentMajorField.setText("");
studentCreditsField.setText("");
textArea.setText("Class and first student added.");
}
else
{
room.addStudent(
new Student(studentFNameField.getText(),
studentLNameField.getText(),
studentIDField.getText(),
studentMajorField.getText(),
Integer.parseInt(studentCreditsField.getText())));
textArea.setText("Next student added.");
studentFNameField.setText("");
studentLNameField.setText("");
studentIDField.setText("");
studentMajorField.setText("");
studentCreditsField.setText("");
}
}
else if(e.getActionCommand().equals("Display"))
{
if (room != null)
{
textArea.setText(room.toString());
}
else
{
textArea.setText("Nothing to display");
}
}
}
}
class Student implements Serializable
{
public String firstName, lastName, studentIdNumber, studentMajor;
public int totalCourseCredits;
//-----------------------------------------------------------------
// Create an empty studentusing a default constructor.
//-----------------------------------------------------------------
public Student ()
{
}
//-----------------------------------------------------------------
// Creates a Student with the specified information.
//-----------------------------------------------------------------
public Student (String name1, String name2, String identification,
String myMajor, int myTotalCredits)
{
firstName = name1;
lastName = name2;
studentIdNumber = identification;
studentMajor = myMajor;
totalCourseCredits = myTotalCredits;
}
//-----------------------------------------------------------------
// Gets and sets first name.
//-----------------------------------------------------------------
public void setFirstName()
{
Scanner scan = new Scanner (System.in);
System.out.println ("Enter your First Name: ");
firstName = scan.nextLine();
}
//-----------------------------------------------------------------
// Gets and sets last name.
//-----------------------------------------------------------------
public void setLastName()
{
Scanner scan = new Scanner (System.in);
System.out.println ("Enter your Last Name: ");
lastName = scan.nextLine();
}
//-----------------------------------------------------------------
// Gets and sets Total Course Credits.
//-----------------------------------------------------------------
public void setTotalCredits()
{
Scanner scan = new Scanner (System.in);
System.out.println ("Enter your Total Credits: ");
totalCourseCredits = scan.nextInt();
}
//-----------------------------------------------------------------
// Gets and sets Student ID Number.
//-----------------------------------------------------------------
public void setIdNumber()
{
Scanner scan = new Scanner (System.in);
System.out.println ("Enter your ID Number: ");
studentIdNumber = scan.nextLine();
}
//-----------------------------------------------------------------
// Gets and sets Student Major.
//-----------------------------------------------------------------
public void setMajor()
{
Scanner scan = new Scanner (System.in);
System.out.println ("Enter your Major: ");
studentMajor = scan.nextLine();
}
public String toString()
{
String s = "First name: " + firstName + "\n" +
"Last name: " + lastName + "\n" +
"StudentID: " + studentIdNumber + "\n" +
"Student Major: " + studentMajor + "\n" +
"Course Creidts: " + totalCourseCredits + "\n";
return s;
}
}
class Classroom implements Serializable
{
private Student[] classRoster;
private int index = 0;
private int capacityStudents, roomNumber;
private String buildingLocation;
//-----------------------------------------------------------------
// Creates an empty Classroom.
//-----------------------------------------------------------------
public Classroom()
{
capacityStudents = 0;
roomNumber = 0;
buildingLocation = "";
}
//-----------------------------------------------------------------
// Creates a Classroom with the specified information.
//-----------------------------------------------------------------
public Classroom(String location, int room, int cap)
{
capacityStudents = cap;
roomNumber = room;
buildingLocation = location;
classRoster = new Student[capacityStudents];
}
//-----------------------------------------------------------------
// Gets and sets Building Location.
//-----------------------------------------------------------------
public void setBuilding()
{
Scanner scan = new Scanner (System.in);
System.out.println ("Enter the Building Location: ");
buildingLocation = scan.next();
}
//-----------------------------------------------------------------
// Gets and sets Room Number.
//-----------------------------------------------------------------
public void setRoomNumber()
{
Scanner scan = new Scanner (System.in);
System.out.println ("Enter the Room Number: ");
roomNumber = scan.nextInt();
}
//-----------------------------------------------------------------
// Sets Capacity of Students.
//-----------------------------------------------------------------
public void setCapacityStudents()
{
Scanner scan = new Scanner (System.in);
System.out.println ("Enter The Capacity of the Classroom: ");
capacityStudents = scan.nextInt();
classRoster = new Student[capacityStudents];
}
//-----------------------------------------------------------------
// Gets Capacity of Students.
//-----------------------------------------------------------------
public int getCapacityStudents()
{
return capacityStudents;
}
//-----------------------------------------------------------------
// Adds an Individual Student to the Classroom, checking if the
// capacity of the clasroom is full.
//-----------------------------------------------------------------
public void addStudent (Student student)
{
if(index < capacityStudents)
{
classRoster[index] = student;
index++;
}
else
{
System.out.println("Capacity exceeded! - Student cannot be added.");
}
}
//-----------------------------------------------------------------
// Adds an Individual Student to the Classroom, checking if the
// capacity of the clasroom is full.
//-----------------------------------------------------------------
public String toString()
{
StringBuffer sb = new StringBuffer
("Building: " + buildingLocation +
"\nClass room: " + roomNumber +
"\nCapacity: " + capacityStudents + "\n\n"
);
for(int i = 0; i < classRoster.length; i++)
{
if(classRoster[i] != null)
sb.append(classRoster[i].toString() + "\n");
}
return sb.toString();
}
}
The error is telling you that index is not available in the scope of the save method. You would need to do something like save.writeObject( classroom.getIndex()) in the save method, if you want to save the index.
You have declared index variable in ClassRoom class. But you are trying to use it in method actionPerformed of ClassRoomFrame class.
Since scope of index is limited to it's enclosing class, it won't be visible in other classes without using instance on ClassRoom class. And that's what compiler error states: cannot find symbol
I have developed a program that is counting the number of lines in a file that is shown below
Scanner in=new Scanner(System.in);
System.out.println("Enter the Drive name like C,D,E etc");
String drive=in.next();
System.out.println("Enter the main folder name");
String main_folder=in.next();
File directory=new File(drive+":"+"//"+main_folder+"//");
Map<String, Integer> result = new HashMap<String, Integer>();
//File directory = new File("C:/Test/");
File[] files = directory.listFiles();
for (File file : files) {
if (file.isFile()) {
Scanner scanner = new Scanner(new FileReader(file));
int lineCount = 0;
try {
for (lineCount = 0; scanner.nextLine() != null; lineCount++);
} catch (NoSuchElementException e) {
result.put(file.getName(), lineCount);
} }}
for( Map.Entry<String, Integer> entry:result.entrySet()){
System.out.println(entry.getKey()+" ==> "+entry.getValue());
}
but I was trying to add a swing interface JFilechooser , I want that user should select the particular folder and all the files inside that folder to be get selected and rest above as my code works as it is , Please advise
Please advise for desiging the jfile chooser so that I can integrate my above code.
I have design one more solution that is
package aa;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.FileDialog;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class FileBrowse extends JFrame {
private JButton browseSwing = new JButton("Choose File");
private JTextField textField = new JTextField(30);
private JButton approve = new JButton("Ok");
public FileBrowse() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600,80);
setResizable(false);
browseSwing.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (arg0.getSource()==browseSwing)
onBrowseSwing();
}});
Container container = getContentPane();
container.setLayout(new FlowLayout());
container.add(browseSwing);
container.add(textField);
container.add(approve);
//pack();
}
protected void onBrowseSwing() {
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showDialog(this, "Open/Save");
if (result == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
textField.setText(file.toString());
String x = file.toString();
fileRead(x);
}
}
public void fileRead(String input){
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(input);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
int count = 0;
int count2 = 0;
//Read File Line By Line
while((strLine = br.readLine())!= null ){
if (strLine.trim().length() != 0){
count++;
}else{
count2++;
}
}
System.out.println("-------Lines Of COdes-------");
System.out.println("number of lines:" + count);
System.out.println("number of blank lines:" + count2);
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
public static void main(String[] args) {
new FileBrowse().setVisible(true);
}
}
but it chooses the individual files I want that all the files to be get selected inside that folder Test
You could use this code (adapted from here):
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("choosertitle");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
Map<String, Integer> result = new HashMap<String, Integer>();
File directory = new File(choosers.getSelectedFile().getAbsolutePath()); //This is where you need to change.
File[] files = directory.listFiles();
for (File file : files)
{
if (file.isFile())
{
Scanner scanner = new Scanner(new FileReader(file));
int lineCount = 0;
try
{
for (lineCount = 0; scanner.nextLine() != null; lineCount++)
;
} catch (NoSuchElementException e)
{
result.put(file.getName(), lineCount);
}
}
}
for (Map.Entry<String, Integer> entry : result.entrySet())
{
System.out.println(entry.getKey() + " ==> " + entry.getValue());
}
}
This code should replace this section:
Scanner in=new Scanner(System.in);
System.out.println("Enter the Drive name like C,D,E etc");
String drive=in.next();
System.out.println("Enter the main folder name");
String main_folder=in.next();
File directory=new File(drive+":"+"//"+main_folder+"//");
Also, just a recommendation, when working with consoles and system paths, you should ideally use File.seperator. This will automatically provide you with the respective system's path separation character.
As per your edit, in your case you are using the fileChooser.getSelectedFile();. This will only get you the file that the user has selected, as per its name. What you should use is the fileChooser.getSelectedFile().getAbsolutePath() and iterate over the files which are within that same directory (as shown above).
EDIT 2: I use this code to display 2 buttons with their respective event handlers:
public static void main(String args[]) {
JFrame frame = new JFrame("Button Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btnExit= new JButton("EXIT");
ActionListener actionListenerExitButton = new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("Exit Button Was Clicked");
}
};
btnExit.addActionListener(actionListenerExitButton);
JButton btnEnter = new JButton("ENTER");
ActionListener actionListenerEnterButton = new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("Enter Button Was Clicked");
}
};
btnEnter.addActionListener(actionListenerEnterButton);
Container contentPane = frame.getContentPane();
contentPane.add(btnExit, BorderLayout.SOUTH);
contentPane.add(btnEnter, BorderLayout.NORTH);
frame.setSize(300, 100);
frame.setVisible(true);
}
All that you need to do now is to plug in the code I have provided earlier in the appropriate event handler.