I know there are duplicate questions of this but I am having trouble applying those solutions to my code. From what I've read it seems the error might be from having multiple scanners? I'm still learning java so I'm not entirely sure. Error is near bottom of code.
outer: for (int i = 0; i < 1000000000; i++) {
String firstUsername = null;
BufferedReader reader;
reader = new BufferedReader(new FileReader(pages));
if (reader.readLine() == null) {
System.out.println("EMPTY");
reader.close();
System.exit(0);
return;
} else {
firstUsername = reader.readLine();
System.out.println(firstUsername);
}
reader.close();
StringBuilder contentBuilder = new StringBuilder();
try (Stream<String> stream = Files.lines(Paths.get("" + accepted + ""), StandardCharsets.UTF_8)) {
stream.forEach(s -> contentBuilder.append(s));
} catch (IOException e1) {
e1.printStackTrace();
}
String users = contentBuilder.toString();
driver.findElement(By.id("com.instagram.android:id/action_bar_search_edit_text")).click();
Thread.sleep(500);
driver.findElement(By.id("com.instagram.android:id/action_bar_search_edit_text"))
.sendKeys(firstUsername);
Thread.sleep(500);
driver.pressKey(new KeyEvent(AndroidKey.BACK));
Thread.sleep(500);
try {
driver.findElement(By.id("com.instagram.android:id/echo_text")).click();
Thread.sleep(500);
} catch (org.openqa.selenium.NoSuchElementException e) {
}
t.tap(PointOption.point(345, 275)).perform(); // accounts
Thread.sleep(500);
try {
By user = By.xpath("//androidx.recyclerview.widget.RecyclerView[#index='0']//*[#text='"
+ firstUsername + "']");
driver.findElement(user).click();
Thread.sleep(2500);
} catch (org.openqa.selenium.NoSuchElementException e) {
Scanner fileScanner = new Scanner(pages);
fileScanner.nextLine();
FileWriter fileStream = new FileWriter(pages);
BufferedWriter out = new BufferedWriter(fileStream);
while (fileScanner.hasNextLine()) {
String next = fileScanner.nextLine();
if (next.equals("\n"))
out.newLine();
else
out.write(next);
out.newLine();
}
out.close();
fileScanner.close();
driver.pressKey(new KeyEvent(AndroidKey.BACK));
Thread.sleep(1000);
t.tap(PointOption.point(970, 150)).perform(); // x
Thread.sleep(500);
continue outer;
}
String decision = "";
Scanner keyInput = null;
if (users.contains(firstUsername)) {
decision = "y";
} else {
keyInput = new Scanner(System.in);
System.out.println("Satisfied user? y or n: ");
decision = keyInput.nextLine();
}
if (decision.matches("n")) {
keyInput.close();
Scanner fileScanner = new Scanner(pages);
fileScanner.nextLine();
FileWriter fileStream = new FileWriter(pages);
BufferedWriter out = new BufferedWriter(fileStream);
while (fileScanner.hasNextLine()) {
String next = fileScanner.nextLine();
if (next.equals("\n"))
out.newLine();
else
out.write(next);
out.newLine();
}
out.close();
fileScanner.close();
FileWriter usernameWriter1 = new FileWriter(declined, true);
usernameWriter1.write(firstUsername);
usernameWriter1.write("\r\n");
usernameWriter1.close();
t.tap(PointOption.point(335, 1835)).perform(); // search
Thread.sleep(500);
t.tap(PointOption.point(525, 130)).perform(); // search bar
Thread.sleep(500);
continue outer;
} else {
// decision = y
FileWriter usernameWriter1 = new FileWriter(used, true);
usernameWriter1.write(firstUsername);
usernameWriter1.write("\r\n");
usernameWriter1.close();
FileWriter usernameWriter2 = new FileWriter(accepted, true);
usernameWriter2.write(firstUsername);
usernameWriter2.write("\r\n");
usernameWriter2.close();
Scanner keyInput1 = new Scanner(System.in);
System.out.println("Remove account? y or n:");
String decision1 = keyInput1.nextLine();
if (decision1.matches("n")) {
removeAccount = false;
keyInput1.close();
} else {
removeAccount = true;
keyInput1.close();
}
if (removeAccount == true) {
Scanner fileScanner = new Scanner(pages);
fileScanner.nextLine();
FileWriter fileStream = new FileWriter(pages);
BufferedWriter out = new BufferedWriter(fileStream);
while (fileScanner.hasNextLine()) {
String next = fileScanner.nextLine();
if (next.equals("\n"))
out.newLine();
else
out.write(next);
out.newLine();
}
out.close();
fileScanner.close();
}
}
MobileElement postCount = (MobileElement) driver
.findElement(By.id("com.instagram.android:id/row_profile_header_textview_post_count"));
String amtPost = postCount.getText();
if (amtPost.matches("0")) {
usingFollowers = true;
driver.findElement(By.id("com.instagram.android:id/row_profile_header_textview_followers_count"))
.click();
Thread.sleep(2500);
break;
} else {
Scanner keyInput2 = new Scanner(System.in);
System.out.println("Use followers or post likers?: f or p");
String decision2 = keyInput2.nextLine(); // ERROR HERE
if (decision2.matches("f")) {
usingFollowers = true;
driver.findElement(
By.id("com.instagram.android:id/row_profile_header_textview_followers_count")).click();
Thread.sleep(2500);
keyInput2.close();
break;
} else {
// none
}
Ive tried
while(keyInput2.hasNextLine()){
System.out.println("Use followers or post likers?: f or p");
String decision2 = keyInput2.nextLine();
if (decision2.matches("f")) {
usingFollowers = true;
driver.findElement(By.id("com.instagram.android:id/row_profile_header_textview_followers_count")).click();
Thread.sleep(2500);
keyInput2.close();
break;
} else {
// none
}
}
But all it did was skip the while loop.
I was correct. I solved the problem by making only one scanner a global variable and handling all inputs through that scanner.
Related
When I delete a record first before inserting a new record, I can do it, and after deleting I can add new record. But if I insert a new record first then my delete function is not working. Based on my research, it's mainly because the input/output is not closed properly but I have already done that, please take a look at my source code thank you.
Insert record
public void RegCustomer()
{
try
{
File F = new File("Customer.txt");
FileWriter fw = new FileWriter(F, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
//PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(F, true)));
pw.println(this.Name+","+this.CheckInDate+","+this.CheckOutDate+","+this.Floor+","+this.RoomID+","+this.ICNumber+","+this.Contact+","+this.Email);
pw.flush();
pw.close();
fw.close();
bw.close();
}
catch(Exception e)
{
}
}
Delete Record
public boolean delcus(String Target)
{
boolean success = false;
File F = new File("Customer.txt");
File Ftc = new File("Temp.txt");
try
{
FileReader fr = new FileReader(F);
BufferedReader br = new BufferedReader(fr);
PrintWriter pr = new PrintWriter(Ftc);
String line = br.readLine();
while (line!=null)
{
String[] wordsinLine = line.split(",");
if (wordsinLine[0].equals(Target))
{
}
else
{
pr.println(line);
success = true;
}
line = br.readLine();
}
if (success)
{
pr.flush();
pr.close();
br.close();
fr.close();
}
}
catch (Exception e)
{
}
F.delete();
File dump = new File("Customer.txt");
Ftc.renameTo(dump);
return success;
}
I have another method that checks for several conditions before triggering the insert method.
public int checkroom()
{
int check = 0;
int ciDay = this.CheckInDate/10000;
int ciMonth = (this.CheckInDate/100)%100;
int coDay = this.CheckOutDate/10000;
int days = coDay - ciDay;
String name;
int Dbcid;
int Dbcod;
int DbFloor;
int DbRoomID;
try
{
File F = new File("Customer.txt");
FileReader Fr = new FileReader(F);
BufferedReader Reader = new BufferedReader(Fr);
Scanner Sc = new Scanner(Reader);
Sc.useDelimiter("[,\n]");
while(Sc.hasNext())
{
name = Sc.next();
Dbcid = Sc.nextInt();
Dbcod = Sc.nextInt();
DbFloor = Sc.nextInt();
DbRoomID = Sc.nextInt();
if (days <= 7)
{
if (DbFloor == this.Floor && DbRoomID == this.RoomID)
{
int DbcidDay = Dbcid/10000;
int DbcidMonth = (Dbcid/100)%100;
int DbcodDay = Dbcod/10000;
if(ciMonth == DbcidMonth)
{
if (ciDay >= DbcidDay && ciDay < DbcodDay)
{
check = 2;
}
else if (coDay >= DbcidDay && coDay < DbcodDay)
{
check = 3;
}
else if (ciDay <= DbcidDay && coDay >= DbcodDay)
{
check = 4;
}
else
{
check = 1;
}
}
else
{
check = 1;
}
}
else
{
check =1;
}
}
else
{
check =5;
}
}
if(check > 0)
{
Sc.close();
Reader.close();
Fr.close();
}
}
catch (Exception e)
{
}
return check;
}
There are a few issues I can see:
You need to close your streams in a finally clause (or, better still, use a try-with-resource). Otherwise, if an exception is thrown that interrupts the normal program flow, your stream will not be closed immediately.
You should only close the outermost stream object (so e.g. your BufferedReader, but not the FileReader)
You are swallowing exceptions. At least do a printStackTrace() on the exceptions you catch so you can see if any are actually thrown.
Avoid methods like File.delete() that don't throw exceptions in the case of an error. Instead, use the equivalent methods on the Files.class, which throw exceptions in the event of an error.
Incidentally, although it's not an issue as such, you don't need to call flush() just before close()-- the latter automatically flushes before closing.
I have a text file which has text as follows:
emVersion = "1.32.4.0";
ecdbVersion = "1.8.9.6";
ReleaseVersion = "2.3.2.0";
I want to update the version number by taking the input from a user if user enter the new value for emVersion as 1.32.5.0 then
emVersion in text file will be updated as emVersion = "1.32.5.0";
All this I have to do using java code. What I have done till now is reading text file line by line then in that searching the word emVersion if found the broken line into words and then replace the token 1.32.4.0 but it is not working because spaces are unequal in the file.
Code what i have written is :
public class UpdateVariable {
public static void main(String s[]){
String replace = "1.5.6";
String UIreplace = "\""+replace+"\"";
File file =new File("C:\\Users\\310256803\\Downloads\\setup.rul");
Scanner in = null;
try {
in = new Scanner(file);
while(in.hasNext())
{
String line=in.nextLine();
if(line.contains("svEPDBVersion"))
{
String [] tokens = line.split("\\s+");
String var_1 = tokens[0];
String var_2 = tokens[1];
String var_3 = tokens[2];
String var_4 = tokens[3];
String OldVersion = var_3;
String NewVersion = UIreplace;
try{
String content = IOUtils.toString(new FileInputStream(file), StandardCharsets.UTF_8);
content = content.replaceAll(OldVersion, NewVersion);
IOUtils.write(content, new FileOutputStream(file), StandardCharsets.UTF_8);
} catch (IOException e) {
}
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//---this code changes each version's values but the is a option to keep the old value.
Scanner in = new Scanner(System.in);
File file = new File("versions.txt");
ArrayList<String> data = new ArrayList<>();
String[] arr =
{
"emVersion", "ecdbVersion", "releaseVersion"
};
String line = "";
String userInput = "";
try (BufferedReader br = new BufferedReader(new FileReader(file));)
{
while ((line = br.readLine()) != null)
{
data.add(line);
}
for (int i = 0; i < arr.length; i++)
{
System.out.println("Please enter new " + arr[i] + " number or (s) to keep the old value.");
userInput = in.nextLine();
line = data.get(i);
String version = line.substring(0, line.indexOf(" "));
if (arr[i].equalsIgnoreCase(version))
{
arr[i] = line.replace(line.subSequence(line.indexOf("= "), line.indexOf(";")), "= \"" + userInput + "\"");
}
if (userInput.equalsIgnoreCase("s"))
{
arr[i] = line;
}
}
PrintWriter printWriter = new PrintWriter(new FileWriter(file, false));
printWriter.println(arr[0]);
printWriter.println(arr[1]);
printWriter.println(arr[2]);
printWriter.close();
}
catch (Exception e)
{
System.out.println("Exception: " + e.getMessage());
}
Use regular expression eg:- line.trim().split("\s*=\s*"); . If it does not work please let me know , i will provide you complete solution.
I'm trying to search a certain string from an input file. Firstly, the code stores data from input file and then it searches the user input data in the text file, but when i try to print one of the variables it ends up being null.
public class Test {
public static void main(String args[])throws IOException, FileNotFoundException {
BufferedReader input = null;
PrintWriter output = null;
try {
input = new BufferedReader (new FileReader ("kolej.txt"));
Scanner in = new Scanner(System.in);
in.useDelimiter("\n");
int index = 0;
String indata = null;
System.out.println("UITM College and Non-Residents Registration System");
System.out.println("Enter your student id: ");
String matrix = in.next();
UITM student[] = new UITM[10];
//storing data into array
while ((indata = input.readLine())!= null) {
StringTokenizer st = new StringTokenizer(indata,";");
student[index] = new Kolej(st.nextToken(), st.nextToken(), st.nextToken(), Integer.parseInt(st.nextToken()), st.nextToken(),Integer.parseInt(st.nextToken()), st.nextToken(),Integer.parseInt(st.nextToken())) ;
index++;
}
//searching
Scanner txtscan = new Scanner(new File("kolej.txt"));
while(txtscan.hasNextLine()) {
matrix = txtscan.nextLine();
if(matrix.indexOf("word") != -1) {
System.out.println(student[0].getName());
}
}
input.close();
output.close();
}
catch (FileNotFoundException fnfe) {
System.out.println("File not found");
}
catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Whatever I did, I did not write a new data on a new line in the file.
How can I fix it?
For example mary's score is 100 and smith's score is 150, but in the txt file it is
mary 100smith 150
I wanna smith 150 in a new line
public class HighScores {
public HighScores(){
String txt = "";
Scanner sc = null;
PrintWriter pw = null;
File Checker = null;
try{
Checker = new File("highScores.txt");
if(!Checker.exists()){
Checker.createNewFile();
}
sc = new Scanner(new File("highScores.txt"));
while(sc.hasNextLine()){
txt = txt.concat(sc.nextLine()+"\n");
}
String score=String.valueOf(Game3.score);
String name = NewPlayer.name;
txt = txt.concat(name + " "+ score +"\n");
pw = new PrintWriter(Checker);// writing the checker
pw.write(txt +"\r\n");
pw.println() gives the same problem too.
}catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}finally{
sc.close();
pw.close();
}
}
}
The code is dodgy, but should actually do what you expect of it.
You are probably viewing the resulting file with a Windows notepad app. It expects "\r\n" as a newline separator, as do most other Windows apps.
Use the following code
public class HighScores {
public HighScores() {
String txt = "";
Scanner sc = null;
PrintWriter pw = null;
File Checker = null;
try {
Checker = new File("highScores.txt");
if (!Checker.exists()) {
Checker.createNewFile();
}
sc = new Scanner(new File("highScores.txt"));
while (sc.hasNextLine()) {
txt = txt.concat(sc.nextLine() + "\n");
}
String score = String.valueOf(Game3.score);
String name = NewPlayer.name;
txt = txt + name + " " + score;
pw = new PrintWriter(Checker);// writing the checker
pw.println(txt);
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
sc.close();
pw.close();
}
}
}
First text file
A.txt;
asdfghjklqw12345 qwe3456789
asdfghjklqw12345 qwe3456789
Second text file
B.txt;
|Record 1: Rejected - Error on table AUTHORIZATION_TBL, column AUTH_DATE.ORA-01843: not a valid month|
|Record 2: Rejected - Error on table AUTHORIZATION_TBL, column AUTH_DATE.ORA-01843: not a valid month|
Third text file
C.txt;
asdfghjklqw12345 qwe3456789 |Record 1: Rejected - Error on table AUTHORIZATION_TBL, column AUTH_DATE.ORA-01843: not a valid month|
asdfghjklqw12345 qwe3456789 |Record 2: Rejected - Error on table AUTHORIZATION_TBL, column AUTH_DATE.ORA-01843: not a valid month|
for the above situation where I want to merge two lines from two different text files into one line.My code is below
List<FileInputStream> inputs = new ArrayList<FileInputStream>();
File file1 = new File("C:/Users/dell/Desktop/Test/input1.txt");
File file2 = new File("C:/Users/dell/Desktop/Test/Test.txt");
FileInputStream fis1;
FileInputStream fis2;
try {
fis1 = new FileInputStream(file1);
fis2= new FileInputStream(file2);
inputs.add(fis1);
inputs.add(fis2);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int total = (int) (file1.length() + file2.length());
System.out.println("total length is " + total);
SequenceInputStream sis = new SequenceInputStream(Collections.enumeration(inputs));
try {
System.out.println("SequenceInputStream.available() = "+ sis.available());
byte[] merge = new byte[total];
int soFar = 0;
do {
soFar += sis.read(merge,total - soFar, soFar);
} while (soFar != total);
DataOutputStream dos = new DataOutputStream(new FileOutputStream("C:/Users/dell/Desktop/Test/C.txt"));
soFar = 0;
dos.write(merge, 0, merge.length);
dos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Here is code:
public class MergeText {
public static void main(String[] args) throws IOException{
String output="";
try(Scanner sc1=new Scanner((new File("A.txt")));
Scanner sc2=new Scanner((new File("B.txt")))){
while(sc1.hasNext() || sc2.hasNext()){
output+=sc1.next() +" "+ sc2.next();
output+="\n";
}
}
try(PrintWriter pw=new PrintWriter(new File("C.txt"))){
pw.write(output);
}
}
}
You might want to have a look at BufferedReader and BufferedWriter.
Show us what you tried and where you are stuck and we are happy to provide more help.
Merging all txt file from a folder can be done in the following way:
public static void main(String[] args) throws IOException {
ArrayList<String> list = new ArrayList<String>();
//Reading data files
try {
File folder = new File("path/inputFolder");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
File file = listOfFiles[i];
if (file.isFile() && file.getName().endsWith(".txt")) {
BufferedReader t = new BufferedReader (new FileReader (file));
String s = null;
while ((s = t.readLine()) != null) {
list.add(s);
}
t.close();
}
}
}
catch (IOException e) {
e.printStackTrace();
}
//Writing merged data file
BufferedWriter writer=null;
writer = new BufferedWriter(new FileWriter("data.output/merged-output.txt"));
String listWord;
for (int i = 0; i< list.size(); i++)
{
listWord = list.get(i);
writer.write(listWord);
writer.write("\n");
}
System.out.println("complited");
writer.flush();
writer.close();
}
Improved on Masudul's answer to avoid compilation errors:
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class MergeText {
public static void main(String[] args) throws IOException {
StringBuilder output = new StringBuilder();
try (Scanner sc1 = new Scanner((new File("C:\\Users\\YourName\\Desktop\\A.txt")));
Scanner sc2 = new Scanner((new File("C:\\Users\\YourName\\Desktop\\B.txt")))) {
while (sc1.hasNext() || sc2.hasNext()) {
String s1 = (sc1.hasNext() ? sc1.next() : "");
String s2 = (sc2.hasNext() ? sc2.next() : "");
output.append(s1).append(" ").append(s2);
output.append("\n");
}
}
try (PrintWriter pw = new PrintWriter(new File("C:\\Users\\mathe\\Desktop\\Fielddata\\RESULT.txt"))) {
pw.write(output.toString());
}
}
}