Replace a character in java? - java

public void sendData(){
try {
URL data = new URL("http://mywebsite.net/isvalid.php?username=" + usernameField.getText() + "&password=" + passwordField.getText());
BufferedReader in = new BufferedReader(
new InputStreamReader(data.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
if(inputLine.length() > 0)
inputString = inputLine;
in.close();
if(!inputString.equals("Incorrect password.")){
System.out.println("Correct password");
run();
dispose();
} else
if(usernameField.getText().length() > 0 && passwordField.getText().length() > 0) {
invalidUP();
System.out.println("Invalid username or password.");
} else
if(usernameField.getText().length() < 1 || (passwordField.getText().length() < 1)) {
System.out.println("No password or username entered.");
upLength();
}
} catch (IOException e) {
e.printStackTrace();
}
}
How would I check if usernameField or passwordField would have a space in it? And if it has, replace it with "_".
Also, if you think this method is wrong to send data or it can be done easier/quicker, please elaborate.

Using String#replaceAll():
String uname ="abc xyz";
uname = uname.replaceAll("\\s+", "_");

Look at String.replace:
passwordField = passwordField.replace(' ', '_');

java.lang.String has a nice method called replaceAll.

If there is only space in your String then try this:
username = username.replace(" " , "_");
Otherwise if there are whitespace in your username then try this:
username = username.replaceAll("\\s+" , "_");

Related

java.net.SocketException: Connection reset by peer. In custom twitch bot

I created custom Twitch bot with using of cavariux library. I called this methods in main class.
bot.setOauth_Key("oauth:key_Value");
bot.connect();
bot.joinChannel(channel.toString());
bot.start();
Approximately one of the 5-6 launches of the bot is accompanied by an exception
java.net.SocketException: Connection reset by peer
. The stack trace indicates that the exception starts on this line.
while ((line = this.reader.readLine( )) != null && !stopped)
in TwitchBot class in method start(). I didn't change code of this library except adding utf encoding in method connect(String ip, int port).
this.writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8));
this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
I've tested my bot on different PCs. On some machines I don't have this issue. On some I got this exception more often.
This is code of method start() in TwitchBot class.
public final void start()
{
if (isRunning()) return;
String line = "";
stopped = false;
try {
while ((line = this.reader.readLine( )) != null && !stopped) {
if (line.toLowerCase( ).startsWith("ping")) {
LOGGER.log(Level.INFO,"> PING");
LOGGER.log(Level.INFO,"< PONG " + line.substring(5));
this.writer.write("PONG " + line.substring(5) + "\r\n");
this.writer.flush();
} else if (line.contains("PRIVMSG"))
{
String str[];
str = line.split("!");
final User msg_user = User.getUser(str[0].substring(1, str[0].length()));
str = line.split(" ");
Channel msg_channel;
msg_channel = Channel.getChannel(str[2], this);
String msg_msg = line.substring((str[0].length() + str[1].length() + str[2].length() + 4), line.length());
LOGGER.log(Level.INFO,"> " + msg_channel + " | " + msg_user + " >> " + msg_msg);
if (msg_msg.startsWith(commandTrigger))
onCommand(msg_user, msg_channel, msg_msg.substring(1));
if (msg_user.toString().equals("jtv") && msg_msg.contains("now hosting")) {
String hoster = msg_msg.split(" ")[0];
onHost(User.getUser(hoster), msg_channel);
}
onMessage(msg_user, msg_channel, msg_msg);
} else if (line.contains(" JOIN ")) {
String[] p = line.split(" ");
String[] pd = line.split("!");
if (p[1].equals("JOIN"))
userJoins(User.getUser(pd[0].substring(1)), Channel.getChannel(p[2], this));
} else if (line.contains(" PART ")) {
String[] p = line.split(" ");
String[] pd = line.split("!");
if (p[1].equals("PART"))
userParts(User.getUser(pd[0].substring(1)), Channel.getChannel(p[2], this));
} else if (line.contains(" WHISPER ")) {
String[] parts = line.split(":");
final User wsp_user = User.getUser(parts[1].split("!")[0]);
String message = parts[2];
onWhisper(wsp_user, message);
} else if (line.startsWith(":tmi.twitch.tv ROOMSTATE")) {
} else if (line.startsWith(":tmi.twitch.tv NOTICE"))
{
String[] parts = line.split(" ");
if (line.contains("This room is now in slow mode. You may send messages every"))
{
LOGGER.log(Level.INFO,"> Chat is now in slow mode. You can send messages every " + parts[15] + " sec(s)!");
} else if (line.contains("subscribers-only mode")) {
if (line.contains("This room is no longer"))
LOGGER.log(Level.INFO,"> The room is no longer Subscribers Only!");
else
LOGGER.log(Level.INFO,"> The room has been set to Subscribers Only!");
} else {
LOGGER.log(Level.INFO,line);
}
} else if (line.startsWith(":jtv MODE "))
{
String[] p = line.split(" ");
if (p[3].equals("+o")) {
LOGGER.log(Level.INFO,"> +o " + p[4]);
} else {
LOGGER.log(Level.INFO,"> -o " + p[4]);
}
} else if (line.toLowerCase().contains("disconnected"))
{
LOGGER.log(Level.INFO, line);
this.connect();
} else
{
LOGGER.log(Level.INFO,"> " + line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
This is code of method connect() in TwitchBot class.
public void connect(String ip, int port)
{
if (isRunning()) return;
try{
if (user == null || user == "")
{
LOGGER.log(Level.SEVERE, "Please select a valid Username");
System.exit(1);
return;
}
if (oauth_key == null || oauth_key == "")
{
LOGGER.log(Level.SEVERE,"Please select a valid Oauth_Key");
System.exit(2);
return;
}
#SuppressWarnings("resource")
Socket socket = new Socket(ip, port);
this.writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8));
this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream(),StandardCharsets.UTF_8));
this.writer.write("PASS " + oauth_key + "\r\n");
this.writer.write("NICK " + user + "\r\n");
this.writer.write("USER " + this.getVersion() + " \r\n");
this.writer.write("CAP REQ :twitch.tv/commands \r\n");
this.writer.write("CAP REQ :twitch.tv/membership \r\n");
this.writer.flush();
String line = "";
while ((line = this.reader.readLine()) != null)
{
if (line.indexOf("004") >= 0) {
LOGGER.log(Level.INFO,"Connected >> " + user + " ~ irc.twitch.tv");
break;
}else {
LOGGER.log(Level.INFO,line);
}
}
} catch (IOException e)
{
e.printStackTrace();
}
}
Thank you for the help
This error means that the peer (i.e. the Twitch server) closes abruptly your connection. See this answer for more details.
I don't know if you can do something to fix that because it can have various external origins (peer crash...). Maybe you can wait and try to reconnect later (note that you might be blacklisted if you connect too often).

Print specific lines(Words/numbers) from csv file

Lets say I have CSV file like this:
Football Contest blabla bla,,,,,,,
Team number1,Team number2,Points team1,Points team2,Red cards
Sweden,France,1,2,"
Sweden,Brazil,3,5,2
Sweden,Germany,2,2,3
Sweden,Spain,3,5,"
And in this file I only want to print out the matches that got red cards. So in this example I would like to print:
Sweden - Brazil = 2 Sweden - Germany = 3
This is my current code, and Im stuck how to move on.
try {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String lines = br.readLine();
String result[] = lines.split(",");
do{
System.out.println();
}while((lines = br.readLine()) != null);
//String result[] = lines.split(",");
//System.out.println(result[1]);
br.close();
}catch (FileNotFoundException e){
System.out.println("File not found : "+ file.toString());
}catch (IOException e ){
System.out.println("Unable to read file: "+ file.toString());
}
EDIT I got helped with:
while (line != null) {
String result[] = line.split(",");
if (result.length == 5) { //red cards present?
System.out.println(result[0] + " - " + result[1] + " " + result[4]);
}
line = br.readLine(); //read next
}
But the problem I have now is that it still prints all because of the " in the csv file. Why cant I do something like this?
if (result[4] == "1,2,3,4,5" ){
System.out.println(result[0] + " - " + result[1] + " " + result[4]);
}
If you the index of red card and it looks like Integer, Then see for that index is integer or not if Yes the print 0,1 and 4
index[0]=Team number1
index[1]=Team number2
index[4]=red cards
Your try-catch block should look like this:
try {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
while (line != null) {
String result[] = line.split(",");
if (result.length == 5 && result[4].matches("[0-9]")) { //red cards present?
System.out.println(result[0] + " - " + result[1] + " " + result[4]);
}
line = br.readLine(); //read next
}
//close readers
br.close();
fr.close();
} catch (FileNotFoundException e) {
System.out.println("File not found : " + file.toString());
} catch (IOException e) {
System.out.println("Unable to read file: " + file.toString());
}
If there are trailing whitespaces in your file, you have to trim the String first: result[4].trim().matches("[0-9]") or use another regex: result[4].matches("\\d\\s")
Why cant I do something like this?
if (result[4] == "1,2,3,4,5" ){
The problem with this is == tests for identity: it will compare if the reference in result[4] is the same reference as the constant in your source code. That expression will always be false. You need to check for equality, not identity:
if (Objects.equals(result[4], "1,2,3,4,5")) {
or
if (result[4] != null && result[4].equals("1,2,3,4,5")) {
or
if ("1,2,3,4,5".equals(result[4])) {
Note that Objects.equals() was (finally) added to the Java standard library in Java 8. Without it, you must guard against a NullPointerException before you call the .equals() method on an object. Traditionally I have preferred the last version because invoking the method on the string literal means I can be assured it is never null and will just work.
You can try like this
public class HelloWorld{
public static void main(String []args){
String str1= "Sweden,Brazil,3,5,4";
String str2="Sweden,Germany,2,2,3";
String str3="Football Contest blabla bla,,,,,,,";
String result1[]=str1.split(",");
String result2[]=str2.split(",");
String result3[]=str3.split(",");
if(result1.length>=5){
System.out.print(result1[0]+"-"+result1[1]+"="+result1[4]);
System.out.println();
}
if(result2.length>=5){
System.out.print(result2[0]+"-"+result2[1]+"="+result2[4]);
System.out.println();
}
if(result3.length>=5){
System.out.print(result3[0]+"-"+result3[1]+"="+result3[4]);
System.out.println();
}
}
}
try this:
do {
if (result[4] instanceof Integer) {
System.out.print(result[0]+"="+result[1]+"="+result[4])
}
} while ((lines = br.readLine()) != null);

How to Update or delete a specific line from a .txt file?

I already have methods to insert data in to a text file and search. now I want methods for 'updating' and 'deleting' a selected record.
this is what I have done so far,
private void InsertbuttonActionPerformed(java.awt.event.ActionEvent evt) {
fileWriter = null;
try {
String phone = Phone.getText();
String fname = Fname.getText();
String lname = Lname.getText();
String nic = NIC.getText();
String city = City.getSelectedItem().toString();
fileWriter = new FileWriter(file, true);
fileWriter.append(phone + "|" + fname + "|" + lname + "|" + nic + "|" + city+ "|");
fileWriter.append("\r\n");
fileWriter.flush();
JOptionPane.showMessageDialog(InsertGUI.this, "<html> " + phone + " <br> Successfully saved! </html>");
Phone.setText(null);
NIC.setText(null);
Fname.setText(null);
Lname.setText(null);
City.setSelectedIndex(0);
} catch (IOException ex) {
Logger.getLogger(InsertGUI.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
fileWriter.close();
} catch (IOException ex) {
Logger.getLogger(InsertGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private void searchbuttonActionPerformed(java.awt.event.ActionEvent evt) {
try {
fileReader = new FileReader(file);
BufferedReader br = new BufferedReader(fileReader);
String selectedphone = SearchF.getText();
String content = "";
String temp = "";
try {
while ((temp = br.readLine()) != null) {
content += temp;
}
} catch (IOException ex) {
Logger.getLogger(UpdateGUI.class.getName()).log(Level.SEVERE, null, ex);
}
HashMap<String, String> map = new HashMap();
StringTokenizer stringTokenizer = new StringTokenizer(content, "|");
boolean found = false;
while (stringTokenizer.hasMoreTokens()) {
String phone = stringTokenizer.nextElement().toString();
String fname = stringTokenizer.nextElement().toString();
String lname = stringTokenizer.nextElement().toString();
String nic = stringTokenizer.nextElement().toString();
String city = stringTokenizer.nextElement().toString();
if (phone.equalsIgnoreCase(selectedphone)) {
Phone.setText(phone);
NIC.setText(nic);
Fname.setText(fname);
Lname.setText(lname);
switch (city) {
case "Ambalangoda":
City.setSelectedIndex(0);
break;
case "Ampara":
City.setSelectedIndex(1);
break;
case "Anuradhapura":
City.setSelectedIndex(2);
break;
case "Avissawella":
City.setSelectedIndex(3);
break;
case "Badulla":
City.setSelectedIndex(4);
break;
case "Balangoda":
City.setSelectedIndex(5);
break;
}
found = true;
}
}
if (!found) {
JOptionPane.showMessageDialog(UpdateGUI.this, "Phone number not found!");
Phone.setText(null);
NIC.setText(null);
Fname.setText(null);
Lname.setText(null);
City.setSelectedIndex(0);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(UpdateGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
can someone please help me with this?
I want methods for:
private void UpdatebuttonActionPerformed(java.awt.event.ActionEvent evt) {
}
private void DeleteButtonActionPerformed(java.awt.event.ActionEvent evt) {
}
Thanks in advance! :)
I give you an example that i found. In this example i will replace a string inside of a line. You can see that in my case im reading from a txt.
/******
public static void replaceSelected(String replaceWith, String type) {
try {
// input the file content to the String "input"
BufferedReader file = new BufferedReader(new FileReader("notes.txt"));
String line;String input = "";
while ((line = file.readLine()) != null) input += line + '\n';
file.close();
System.out.println(input); // check that it's inputted right
// this if structure determines whether or not to replace "0" or "1"
if (Integer.parseInt(type) == 0) {
input = input.replace(replaceWith + "1", replaceWith + "0");
}
else if (Integer.parseInt(type) == 1) {
input = input.replace(replaceWith + "0", replaceWith + "1");
}
// check if the new input is right
System.out.println("----------------------------------" + '\n' + input);
// write the new String with the replaced line OVER the same file
FileOutputStream fileOut = new FileOutputStream("notes.txt");
fileOut.write(input.getBytes());
fileOut.close();
} catch (Exception e) {
System.out.println("Problem reading file.");
}
}
public static void main(String[] args) {
replaceSelected("Do the dishes","1");
}
*/
Result:
Original:
Original Text File Content:
Do the dishes0
Feed the dog0
Cleaned my room1
Output:
Do the dishes0
Feed the dog0
Cleaned my room1
Do the dishes1
Feed the dog0
Cleaned my room1
Recent output:
Do the dishes1 (HAS BEEN CHANGED)
Feed the dog0
Cleaned my room1
Maybe this example helps for you.
Regards!
Read data to string. Use string.replace(forDelte,""). And then just rewrite to txt file.

Not reading from the file correctly in Java

I'm trying to make a game and I am sorting out the account's and im doing it in text files at the moment as im just playing around, the text file for example is,
username
password
and when I run the code below , it runs the else statement every time when the details I enter are correct.
String player;
Scanner loadPlayer = new Scanner(System.in);
System.out.print("Enter Username: ");
String username = loadPlayer.nextLine();
System.out.println();
System.out.print("Enter Passwork: ");
String password = loadPlayer.nextLine();
System.out.println();
try {
File file = new File("/home/kieran/Desktop/project/accounts/"+username+".txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
String userData[] = stringBuffer.toString().split("\n");
System.out.println(userData[0]);
System.out.println(userData[1]);
if (userData[0] == username && userData[1] == password){
player = username;
System.out.println(player);
}
else{
System.out.println("Username, "+username+" does not exist, please try again!");
loadPlayer();
}
} catch (IOException e) {
e.printStackTrace();
}
if (userData[0].equals(username) && userData[1].equals(password)){
player = username;
System.out.println(player);
}
Your string comparison implementation is not OK.
Replace this line
if (userData[0] == username && userData[1] == password){
with this one:
if (userData[0].trim().equals(username.trim()) && userData[1].trim().equals(password.trim())){
try this
if (userData[0].equals(username) && userData[1].equals(password)){
player = username;
System.out.println(player);
}
else{
System.out.println("Username, "+username+" does not exist, please try again!");
loadPlayer();
}

Why does this `do-while/for loop` never end if you give an invalid input?

I have a for loop nested inside a do-while loop which is to read through a text file and look for the given input. I have noticed that it works perfectly fine if you give an input which exists in the file, however can someone help me understand why the program never exits the loop if you give an input which does not exist in the text file, even though it should exit when the variable with the text from the file becomes null. I have posted all relevant code from the method where the for loop is being executed, including the part where it gains the user input; just to be clear, there are no errors given when compiling or running the program.
FileReader fileReader = new FileReader("VirtualATM.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
System.out.print("Enter your pin: ");
char [] EnterPin = {0, 0, 0 ,0};
try{
EnterPin = System.console().readPassword();
}catch(InputMismatchException e){
e.printStackTrace();
System.out.println(e.getMessage());
//System.out.println(e.getLocalizedMessage());
}
boolean pinTrue = false;
String LineFromFile = null;
LineFromFile = bufferedReader.readLine();
String [] PinSearch = LineFromFile.split("\\s+");
String UserPin = java.util.Arrays.toString(EnterPin);
String PinMod = UserPin.replaceAll("\\[", "");
String PinMod2 = PinMod.replaceAll("\\,", "");
String PinMod3 = PinMod2.replaceAll("\\s+", "");
String PinToWrite = PinMod3.replaceAll("\\]", "");
do{
for(int search = 0; search < PinSearch.length; search++){
String SearchForPin = PinSearch[search];
if(SearchForPin.matches(PinToWrite)){
pinTrue = true;
System.out.println("Success!");
}
else if(search => PinSearch.length){
System.out.println("Error! Invalid pin.");
}
}
LineFromFile = bufferedReader.readLine();
}while(pinTrue == false && line != null);
}catch(IOException e){
e.printStackTrace();
System.out.println(e.getLocalizedMessage());
}
You need to move the line processing to be inside the loop, after each line you read. Otherwise, you only process the first line you read before the loop.
do{
for(int search = 0; search < PinSearch.length; search++){
String SearchForPin = PinSearch[search];
if(SearchForPin.matches(PinToWrite)){
pinTrue = true;
System.out.println("Success!");
}
else if(search => PinSearch.length){
System.out.println("Error! Invalid pin.");
}
}
LineFromFile = bufferedReader.readLine();
if (LineFromFile != null) {
PinSearch = LineFromFile.split("\\s+");
UserPin = java.util.Arrays.toString(EnterPin);
PinMod = UserPin.replaceAll("\\[", "");
PinMod2 = PinMod.replaceAll("\\,", "");
PinMod3 = PinMod2.replaceAll("\\s+", "");
PinToWrite = PinMod3.replaceAll("\\]", "");
}
} while(pinTrue == false && LineFromFile != null);
Because you're testing line, but reading into LineFromFile.
Change this
}while(pinTrue == false && line != null);
to something like
}while(!pinTrue && LineFromFile != null);
And, as Eran notes here, your line processing logic should be in the body of the do, so
do{
String LineFromFile = bufferedReader.readLine();
String [] PinSearch = LineFromFile.split("\\s+");
String UserPin = java.util.Arrays.toString(EnterPin);
String PinMod = UserPin.replaceAll("\\[", "");
String PinMod2 = PinMod.replaceAll("\\,", "");
String PinMod3 = PinMod2.replaceAll("\\s+", "");
String PinToWrite = PinMod3.replaceAll("\\]", "");

Categories

Resources