Java, passing values between classes - java

Ok so I'm a noob at Java and this just got me.
I have a button that calls a class in which some background code runs to check if the tape drive is online, offline or busy.
Button Code:
private void btnRunBckActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
btnRunBackup runBackupObject = new btnRunBackup();
runBackupObject.checkStatus();
lblRunBck.setText("Errors go here");
}
Then I have my separate class file btnRunBackup.
public class btnRunBackup{
public void checkStatus(){
/*
Here I simply create a tempfile and run some
linux commands via getRuntime and print the
output to the tempfile
Then I call my second method passing the
absolute file path of the tempfile
*/
this.statusControl(path);
}catch(IOException e){
e.printStackTrace();
public void statusControl(String param) throws FileNotFoundException, IOException{
/*
Here I use BufferedReader to go through the
tempfile and look for as series of 3
different strings.
I use a if else if statement for flow control
depending on what string was found.
string 1 will call a new Jframe
if string 2, 3 or none of them are found the
is where I am stuck at
}
}
I want to return a String value back to btnRunBckActionPerformed().
The reason is lblRunBck will initially show no text at all but for instance the user clicks on the button and the resource happens to be busy then i want to run lblRunBck.setText(param); on lblRunBck while refusing the user permission to continue
private void btnRunBckActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String text;
btnRunBackup runBackupObject = new btnRunBackup();
runBackupObject.checkStatus();
lblRunBck.setText("Errors go here");
}
here is my btnRunBackup class
public class btnRunBackup {
private String s;
public void checkStatus() {
String s, path = null;
Process p;
try{//try1
//create a temp file named tempfilexxx.tmp
File temp = File.createTempFile("tempfile", ".tmp");
//get file path
path = temp.getAbsolutePath();
System.out.println("checkStatus: " + path);
//write to tempfilexxx.tmp
BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
try{// try2
//set p = to the content of ls home
p = Runtime.getRuntime().exec("ls /home | grep ariel");
BufferedReader br = new BufferedReader(
new InputStreamReader(p.getInputStream()));
//write content of p to tempfilexxx.tmp line by line
while ((s = br.readLine()) != null)
bw.write(s + "\n");
//close BufferedReader
br.close();
}catch (Exception e){} //END OF try2
//close BufferedWriter
bw.close();
/*
Now that we ran the 'mt -f /dev/nst0 status command under home we
will filter for one of the following strings
(for testing we will use ls -la /home and filter for ariel)
We will do this by calling the checkStatus method
*/
this.statusControl(path);
}catch(IOException e){
e.printStackTrace();
}// END OF try1
}// END OF listDir
//throws FileNotFoundException for bufferedReader if file not found
public void statusControl(String param) throws FileNotFoundException, IOException{
/*
On production code there will be 4 possible conditions:
1. ONLINE - ready to write (currently we will use ariel)
2. DR_OPEN - no tape available
3. /dev/nst0: Device or resource busy - resource bussy
4. If other than stated above give error 1000
*/
System.out.println("statusControl: " + param);
String ONLINE = "arielvz",
OPEN = "DR_OPEN",
BUSSY = "Device or resource busy",
sCurrentLine;
//Scan file line by line for one of the above options
BufferedReader br = new BufferedReader(new FileReader(param));
while ((sCurrentLine = br.readLine()) != null){
//Tape is online and ready for writing
if (sCurrentLine.contains(ONLINE)){
System.out.println("found ariel");
}
//There is no tape in the tape drive
else if (sCurrentLine.contains(OPEN)){
//lblRunBck should tell the user to put a tape in the drive
System.out.println("No tap in tape drive");
}
else if (sCurrentLine.contains(BUSSY)){
//lblRunBck should notify user that the resource is in use
System.out.println("Device or resource bussy");
}
else{
//Something unexpected happend
System.out.println("Error 1001: Please notify Administrator");
}
}
}//END OF statusControl
public String returnHandler(String param){
return param;
}
}
Maby This will make it more clear

If you want checkStatus to return a status, then do not make it returning nothing (a void function)
public class btnRunBackup {
private String s;
public void checkStatus() {
but make it returning error as a String like:
public class btnRunBackup {
private String s;
public String checkStatus() {
String error = null; // by default no error
... do whatever you need to find out the error
....
error = "error is: xxx ";
return error; // return null (no error ) or what you found
}
change you logic in you calling code to display what error have been returned by checkStatus
private void btnRunBckActionPerformed(java.awt.event.ActionEvent evt)
{
// TODO add your handling code here:
String error;
btnRunBackup runBackupObject = new btnRunBackup();
error = runBackupObject.checkStatus();
lblRunBck.setText(error == null ? "No error" : error);
}

Related

Java: How do I iterate through a file with multiple lines, then extract specific lines after filtering delimiters?

Clarification: I have a text file with multiple lines and I want to separate specific lines into fields for an object.
I have been banging my head against a wall for about 3 days now, and I feel as if I'm overthinking this.
import java.io.*;
import java.util.*;
public class ReadFile {
public static void main(String[] args) throws FileNotFoundException {
String fileName = null;
Scanner input = new Scanner(System.in);
System.out.print("Enter file path: ");
fileName = input.nextLine();
input.close();
String fileText = readFile(fileName);
System.out.println(fileText);
}
public static String readFile(String fileName) throws FileNotFoundException {
String fileText = "";
String lineText = "";
File newFile = new File(fileName);
if (newFile.canRead()) {
try (Scanner scanFile = new Scanner(newFile)) {
while (scanFile.hasNext()) {
lineText = scanFile.nextLine();
if (lineText.startsWith("+")) {
}
else {
fileText = fileText + lineText + "\n";
}
}
} catch (Exception e) {
System.out.println(e);
}
} else {
System.out.println("No file found. Please try again.");
}
return fileText;
}
}
My goal is to take a file that looks similar to this (this is the whole file, imagine a .txt with exactly this in it):
Name of Person
----
Clothing:
Graphic TeeShirt
This shirt has a fun logo of
depicting stackoverflow and a horizon.
****
Brown Slacks
These slacks reach to the floor and
barely cover the ankles.
****
Worn Sandals
The straps on the sandals are frayed,
and the soles are obviously worn.
----
Then I need to extract the top line (e.g.: "Graphic TeeShirt") as a type of clothing the object is wearing, then "This shirt has a fun [...]" as the description of that object.
I have another .java with setters/getters/constructors, but I can't figure out how to iterate through the text file.
Edit: I know I loop through each line, but I need to create an object that has the person's name as a field, the item name (Graphic TeeShirt) as a field, then the description under the item as the next field. Then the next object will be a new object with person's name as a field, the next item (Brown Slacks) as a field, then the description as a field.
I don't know how to separate the lines in to the fields I need.
As I mentioned, the data file format is lousy, which is the real source of the problem, but your delimiters can be used to help out a little. You might approach the problem this way. Obviously don't dump your code like I've done into main but this might start you off. You still need to separate the clothing names from their descriptions but you should get the idea from the below. You can then start making a pojo out of the data.
Pass the path to your data file to this app and look out for the metadata debug outputs of 'Name' and 'Item'.
import java.util.Scanner;
import java.nio.file.Paths;
public class PersonParser {
public static void main(String[] args) {
try {
try (Scanner scPeople = new Scanner(Paths.get(args[0]))) {
scPeople.useDelimiter("----+");
int tokenCount = 0;
while (scPeople.hasNext()) {
String token = scPeople.next();
if (tokenCount % 2 == 0) {
System.out.printf("Name: %s", token);
} else {
// Parse clothing
Scanner scClothing = new Scanner(token);
scClothing.useDelimiter("\\*\\*\\*+");
while (scClothing.hasNext()) {
String item = scClothing.next();
System.out.printf("Item: %s", item);
}
}
tokenCount++;
}
}
} catch (Throwable t) {
t.printStackTrace();
}
}
}
The following code is according to the details in your question, namely:
The sample file in your question is the entire file.
You want to create instances of objects that have the following three attributes:
Person's name.
Name of an item of clothing.
Description of that item.
Note that rather than ask the user for the name of the file, I simply use a hard-coded file name. Also note that method toString, in the below code, is simply for testing purposes. The code also uses try-with-resources and method references.
public class ReadFile {
private static final String DELIM = "****";
private static final String LAST = "----";
private String name;
private String item;
private String description;
public void setName(String name) {
this.name = name;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public void setDescription(String description) {
this.description = description;
}
public String toString() {
return String.format("%s | %s | %s", name, item, description);
}
public static void main(String[] strings) {
try (FileReader fr = new FileReader("clothing.txt");
BufferedReader br = new BufferedReader(fr)) {
String line = br.readLine();
String name = line;
br.readLine();
br.readLine();
line = br.readLine();
String item = line;
List<ReadFile> list = new ArrayList<>();
ReadFile instance = new ReadFile();
instance.setName(name);
instance.setItem(item);
line = br.readLine();
StringBuilder description = new StringBuilder();
while (line != null && !LAST.equals(line)) {
if (DELIM.equals(line)) {
instance.setDescription(description.toString());
list.add(instance);
instance = new ReadFile();
instance.setName(name);
description.delete(0, description.length());
}
else {
if (instance.getItem() == null) {
instance.setItem(line);
}
else {
description.append(line);
}
}
line = br.readLine();
}
if (description.length() > 0) {
instance.setDescription(description.toString());
list.add(instance);
}
list.forEach(System.out::println);
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}
Running the above code produces the following output:
Name of Person | Graphic TeeShirt | This shirt has a fun logo ofdepicting stackoverflow and a horizon.
Name of Person | Brown Slacks | These slacks reach to the floor andbarely cover the ankles.
Name of Person | Worn Sandals | The straps on the sandals are frayed,and the soles are obviously worn.
It's not clear what you want to achieve and what is your issue exactly. You said that you can't figure out how to iterate through a text file, so let's dive into this fairly straightforward task.
In general, you have a valid, but the overcomplicated method for reading a file. Modern versions of Java provide a lot simpler methods and it's better to use them (only if you're not implementing some test task to understand how everything is working under the hood).
Please see my example below for reading a file line by line using Java NIO and Streams APIs:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
import java.util.stream.Stream;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter file path: ");
String fileName = input.nextLine();
input.close();
Path path = Paths.get(fileName);
try (Stream<String> lines = Files.lines(path)) {
lines.filter(line -> {
// filter your lines on some predicate
return line.startsWith("+");
});
// do the mapping to your object
} catch (IOException e) {
throw new IllegalArgumentException("Incorrect file path");
}
}
}
This should allow you to filter the lines from your files based on some predicate and later to the mapping to your POJO if you intend to do so.
If you have any other issues besides reading the file and filtering its content, please add clarification to your questions. Preferably, with examples and test data.

How to write a Strings data to a text file - Java

I have this account creation program I'm working on, and would love to save the persons name, last name, email and password to a text file. The following snippet should do just that, but the error message I'm getting when I put a String variable in the .write method is, "no suitable method found for write(JTextFeild)".
private void signupActionPerformed(java.awt.event.ActionEvent evt) {
fname.getText();
lname.getText();
email.getText();
reemail.getText();
password.getText();
repassword.getText();
if(male.equals(true)) {
males = true;
}
if(female.equals(true)) {
females = true;
}
BufferedWriter writer = null;
try {
writer = new BufferedWriter( new FileWriter("UserPass.txt"));
writer.write(fname);
}
catch ( IOException e) {
}
finally {
try {
if ( writer != null) {
writer.close( );
}
}
catch ( IOException e) {
}
}
}
Any ideas on how to fix this?
From the documentation of getText() in javax.swing.text.JTextComponent:
public String getText()
JTextField is just the GUI element, getText() doesn't change it.
You should store the result in a String variable and then use it to write().

How to display a text from a file on a WizardPage

I've been trying to read a text from a file and display it on my WizardPage.
It cannot be displayed but when I type the Text manually it shows the string.
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class Read_file {
// create ArrayList to store the information of a wizardPage
public List<Inventory> invItem = new ArrayList<>();
public read_file(String file_name) {
try {
// create a Buffered Reader object instance with a FileReader
BufferedReader br = new BufferedReader(new FileReader(file_name));
// read the first line from the text file
String fileRead = br.readLine();
// loop until all lines are read
while (fileRead != null) {
// use string.split to load a string array with the values from
// each line of
// the file, using a comma as the delimiter
String[] tokenize = fileRead.split(":");
// assume file is made correctly
// and make temporary variables for the three types of data
String Name = tokenize[0];
String Next = tokenize[1];
String Story = tokenize[2];
// creat temporary instance of Inventory object
// and load with three data values
Inventory tempObj = new Inventory(Name, Next, Story);
// add to array list
invItem.add(tempObj);
// read next line before looping
// if end of file reached
fileRead = br.readLine();
}
// close file stream
br.close();
}
// handle exceptions
catch (FileNotFoundException fnfe) {
System.out.println("file not found");
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
This is my Wizard :
public class Wizard_main extends Wizard {
Page first;
Page third;
end End;
Read_file read=new Read_file("wizard.txt");
String story1=read.invItem.get(0).Story; // **this string cannot be displayed**
String story2="After a couple of hours, Jack woke up..."; //this one
works fine
public void addPages(){
first= new Page("S1",story1);
third=new Page("S2",story2);
End= new end("END");
first.setNextPage("S2", "S3");
third.setNextPage("S2", "S1");
addPage(First);
addPage(Third);
addPage(End);
}
#Override
public boolean performFinish() {
// TODO Auto-generated method stub
return true;
}}
I'm having "java.lang.IndexOutOfBoundsException" when I try to display a text from a file on my WizardPage.
Stack trace : !MESSAGE Unhandled event loop exception
!STACK 0
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
Note: The Text is properly displayed while using System.out.println() in another class
A solution which I used is as following :
private String getJsonFilePath(String fileName) {
String filePath = "";
// Reading file within the plugin
Bundle bundle = Platform.getBundle("com.eclipseplugin.sics");
// Get the wizard file from the plugin location.
URL fileURL = bundle.getEntry("lib/" + fileName + ".json");
try {
filePath = FileLocator.resolve(fileURL).getPath().substring(1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return filePath;
}
This is how FileLocator should be used.

How to create fixed format file using FixedFormat4j Java Library?

I am able to load files in Fixed Format but unable to write a fixed format file using FixedFormat4j.
Any idea how to do that?
public class MainFormat {
public static void main(String[] args) {
new MainFormat().start();
}
private FixedFormatManager manager;
public void start(){
System.out.println("here");
manager = new FixedFormatManagerImpl();
try {
BufferedReader br = new BufferedReader(new FileReader("d:/myrecords.txt"));
System.out.println("here1");
String text;
MyRecord mr = null;
while ((text = br.readLine()) != null) {
mr = manager.load(MyRecord.class, text);
System.out.println(""+mr.getAddress() + " - "+mr.getName());
}
mr.setName("Rora");
manager.export(mr);
} catch (IOException | FixedFormatException ex) {
System.out.println(""+ex);
}
}
}
I have seen export method but don't understand how to use it? Nothing happens in above code
The export method returns a string representing the marshalled record.
In your code you would need to write out the result of the export command to a FileWriter. So:
before the while loop:
FileWriter fw = new FileWriter("d:/myrecords_modified.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
after the while loop:
mr.setName("Rora");
String modifiedRecord = manager.export(mr);
bw.write(modifiedRecord);

Pircbot getting gettin text from txt file into command

Hello i'm working on a Irc Bot for Twich and i wanna add a command that gets text from a txt file and uses it in a command
EX: user type's "!song" in chat -> bot get the song title from a txt file and say's in chat the Song title.
i got the part working that gets the data from the txt file but i cant get that data in the command.
import org.jibble.pircbot.*;
import java.io.BufferedReader;
import java.io.FileReader;
public class MprovBot extends PircBot
{
// Get song title from Txt file
public static void main(String[] args) throws Exception {
FileReader file = new FileReader ("song.txt");
BufferedReader reader = new BufferedReader(file);
String song = "";
String line = reader.readLine();
while (line != null){
song += line;
line = reader.readLine();
}
System.out.println(song);
}
// IRC Commands_
public MprovBot() {
this.setName("MprovBot");
}
public void onMessage(String channel, String sender,
String login, String hostname, String message) {
if (message.equalsIgnoreCase("!test")) {
sendMessage (channel, "Test Done");
}
if (message.equalsIgnoreCase("!Command")) {
sendMessage (channel, "This are the commands you can do.");
}
if (message.equalsIgnoreCase("!song")){
sendMessage (channel, song);
}
}
}
when i try to compile the code i get this
MprovBot.java:40: error: cannot find symbol
sendMessage (channel, song);
^
symbol: variable song
location: class MprovBot
1 error
The variable song is not defined in the onMessage() method. So the compiler can't find the variable. What you have to do is to change the main method to a normal method with a return type, and call this method on receiving the !song command.
public class MprovBot extends PircBot {
// Get song title from Txt file AND return it!
public String getSong() throws Exception {
FileReader file = new FileReader ("song.txt");
BufferedReader reader = new BufferedReader(file);
String song = "";
String line = reader.readLine();
while (line != null){
song += line;
line = reader.readLine();
}
return song;
}
// IRC Commands_
public MprovBot() {
this.setName("MprovBot");
}
public void onMessage(String channel, String sender,
String login, String hostname, String message) {
if (message.equalsIgnoreCase("!test")) {
sendMessage (channel, "Test Done");
}
if (message.equalsIgnoreCase("!Command")) {
sendMessage (channel, "This are the commands you can do.");
}
if (message.equalsIgnoreCase("!song")){
String song = "";
try {
song = getSong();
} catch(Exception e) { e.printStackTrace(); }
sendMessage (channel, song);
}
}
}

Categories