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);
}
}
}
Related
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.
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);
}
I'm working on a homework assignment and have run into an odd "ArrayOutOfBoundsException" error - I know what the error means (essentially I'm trying to reference a location in an array that isn't there) but I'm not sure why it's throwing that error? I'm not sure what I'm missing, but obviously there must be some logic error somewhere that I'm not seeing.
PhoneDirectory.java
import java.util.HashMap;
import java.io.*;
class PhoneDirectory {
private HashMap<String, String> directoryMap;
File directory;
public PhoneDirectory() { //create file for phone-directory
directory = new File("phone-directory.txt");
directoryMap = new HashMap<String, String>();
try(BufferedReader buffer = new BufferedReader(new FileReader(directory))) {
String currentLine;
while((currentLine = buffer.readLine()) != null) { //set currentLine = buffer.readLine() and check if not null
String[] fileData = currentLine.split(","); //create array of values in text file - split by comma
directoryMap.put(fileData[0], fileData[1]); //add item to directoryMap
}
}
catch(IOException err) {
err.printStackTrace();
}
}
public PhoneDirectory(String phoneDirectoryFile) {
directory = new File(phoneDirectoryFile);
directoryMap = new HashMap<String, String>();
try(BufferedReader buffer = new BufferedReader(new FileReader(directory))) {
String currentLine;
while((currentLine = buffer.readLine()) != null) { //set currentLine = buffer.readLine() and check if not null
String[] fileData = currentLine.split(","); //create array of values in text file - split by comma
directoryMap.put(fileData[0], fileData[1]); //add item to directoryMap
}
}
catch(IOException err) {
err.printStackTrace();
}
}
public String Lookup(String personName) {
if(directoryMap.containsKey(personName))
return directoryMap.get(personName);
else
return "This person is not in the directory.";
}
public void AddOrChangeEntry(String name, String phoneNumber) {
//ASK IF "IF-ELSE" CHECK IS NECESSARY
if(directoryMap.containsKey(name))
directoryMap.put(name,phoneNumber); //if name is a key, update listing
else
directoryMap.put(name, phoneNumber); //otherwise - create new entry with name
}
public void DeleteEntry(String name) {
if(directoryMap.containsKey(name))
directoryMap.remove(name);
else
System.out.println("The person you are looking for is not in this directory.");
}
public void Write() {
try(BufferedWriter writeDestination = new BufferedWriter(new FileWriter(directory)))
{
for(String key : directoryMap.keySet())
{
writeDestination.write(key + ", " + directoryMap.get(key) + '\n');
writeDestination.newLine();
}
}
catch(IOException err) {
err.printStackTrace();
}
}
}
Driver.java
public class Driver {
PhoneDirectory list1;
public static void main(String[] args) {
PhoneDirectory list1 = new PhoneDirectory("test.txt");
list1.AddOrChangeEntry("Disney World","123-456-7890");
list1.Write();
}
}
Essentially I'm creating a file called "test.txt" and adding the line "Disney World, 123-456-7890" - what's weird is that the code still works - but it throws me that error anyway, so what's really happening? (For the record, I'm referring to the line(s): directoryMap.put(fileData[0], fileData[1]) - which would be line 14 and 28 respectively.)
I am new to Android and I want to play online radio (example link http://www.bbc.co.uk/radio/listen/live/r1_aaclca.pls) using ParsePls. I have PlsParse code but after this I don't know how to play using the player in Android.
PlsParser.java
public PlsParser(File file) throws FileNotFoundException {
this.reader = new BufferedReader(new FileReader(file), 1024);
}
#Override
public List<String> getUrls() {
LinkedList<String> urls = new LinkedList<String>();
while (true) {
try {
String line = reader.readLine();
if (line == null) {
break;
}
String url = parseLine(line);
if (url != null && !url.equals("")) {
urls.add(url);
}
} catch (IOException e) {
e.printStackTrace();
}
}
return urls;
}
private String parseLine(String line) {
if (line == null) {
return null;
}
String trimmed = line.trim();
if (trimmed.indexOf("http") >= 0) {
return trimmed.substring(trimmed.indexOf("http"));
}
return "";
}
}
and
PlaylistParser.java
public interface PlaylistParser {
public List<String> getUrls();
}
Basically I need to play online fm in Android. How can I do this?
I got some solution without Parse pls,
Just Enter URL of pls file in browser(example link yp.shoutcast.com/sbin/tunein-station.pls?id=213352),
you will get download "tunein-station.pls",
Just open the downloaded file with notepad,
you can see
[playlist]
numberofentries=2
File1=http://208.115.222.205:9938
Title1=(#1 - 1/100) RADIO CITY TAMIL
Length1=-1
File2=http://208.115.222.205:9948
Title2=(#2 - 67/300) RADIO CITY TAMIL
Length2=-1
Version=2
Here File1 URL(shoutcast online radio url)
Now using this URL i coded with mediaplayer.
I have a text file that has is set out like the following
Title - Welcome to the Dibb
Date - 13/03/11
Information - Hello and welcome to our website.
Title - Welcome to student room
Date - 06/05/11
Information - Hello and welcome to the student room. We are a online forum that allows previous and current students to ask questions.
I need to parse this text file and save things like the title line, date line and the rest will be saved as information. I know how to read the file and save the full file as a string but I am stuck on getting the select information.
CODE
This is the code I have used to read the text file
helloTxt.setText(readTxt());
}
private String readTxt() {
InputStream inputStream = getResources().openRawResource(R.raw.pages);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1) {
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String str = byteArrayOutputStream.toString();
return str;
}
Read file line by line
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
// process the line.
}
br.close();
If you can guarantee that every line has as maximum one - then you can use following pattern.
String[] tokens = line.split("\s-\s");
For this line
Title - Welcome to the Dibb
It would give you
tokens[0] = "Title";
tokens[1] = "Welcome to the Dibb";
I try to write some classes which can help you to approach your issue
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class Test4 {
private List<Information> parser(String data) {
List<Information> informations = new ArrayList<Information>();
String blocks[] = data.split("\n\r");
for(String block : blocks) {
String[] lines = block.split("\n");
Information information = new Information();
information.setTitle((lines[0].split("-"))[1].trim());
information.setDate((lines[1].split("-"))[1].trim());
information.setInfo((lines[2].split("-"))[1].trim());
informations.add(information);
}
return informations;
}
private void runner() throws IOException {
InputStream inputStream = getClass().getResourceAsStream("input.txt");
String input = "";
int cc;
while((cc = inputStream.read()) != -1) {
input += (char) cc;
}
List<Information> informations = parser(input);
for(Information information : informations) {
System.out.println(information);
}
}
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
Test4 test4 = new Test4();
test4.runner();
}
class Information {
private String title;
private String date;
private String info;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
#Override
public String toString() {
return "Information [" + (title != null ? "title=" + title + ", " : "")
+ (date != null ? "date=" + date + ", " : "") + (info != null ? "info=" + info : "") + "]";
}
}
}