Application not writing file - java

As a beginner, I am trying to print a set of info to a file called "Sign_in.txt" but this code only creates the file and doesn't print anything. What am I doing wrong?
String nu="CUSTOMER DETAILS START";
String enu="CUSTOMER DETAILS END";
n=namefield.getText();
a=agefield.getText();
ad=adfield.getText();
s=salfield.getText();
p=phfield.getText();
d=dobfield.getText();
e=emfield.getText();
ArrayList<String> list = new ArrayList<String>();
list.add(nu);
list.add(n);
list.add(a);
list.add(ad);
list.add(s);
list.add(p);
list.add(d);
list.add(e);
list.add(u);
list.add(q);
list.add(enu);
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("Sign_in.txt",true)))) {
Writer output = new BufferedWriter(out);
int l = list.size();
for(int i = 0; i<l; i++){
output.write(list.get(i).toString()+"\n");
}
output.close();
}
catch (Exception e)
{
e.printStackTrace();
}
JOptionPane.showMessageDialog(this,"Thank you for registering");
System.exit(0);
new accpage().setVisible(true);
}

I would have something like this:
try (PrintWriter output =
new PrintWriter(new BufferedWriter(new FileWriter("Sign_in.txt"))))
{
for (String line: list) {
output.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}

Working code
try (PrintWriter output = new PrintWriter(
new BufferedOutputStream(
new FileOutputStream("Sign_in.txt")), true))
{
int l = list.size();
for (int i = 0; i < l; i++) {
output.println(list.get(i).toString());
}
} catch (Exception e) {
e.printStackTrace();
}

Related

java error: java.util.NoSuchElementException: No line found

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.

How to read file until a specific element

I'm facing a problem that I can't (more likely I don't know how to) read a file until a specific element.
My file looks like:
Vaga
Senieji Amatai, 2016, 5,4
Humanitas
Kolumbas, 1980, 3
Programavimas Java, 2016, 14,56
And any ideas how to stop it reading at 5,4?
Here's a little part of my code:
File FILE = new File(duomenuFailas);
if (FILE.exists() && FILE.length() > 0) {
try {
Scanner SC = new Scanner(FILE);
for (int i = 0; i < FILE.length(); i++) {
if (SC.hasNextLine()) {
String[] parodyti = SC.nextLine().split(",");
System.out.println(parodyti[0]);
}
}
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
Try something like that:
File file = new File(duomenuFailas);
if (file.isFile()) {
try {
try (Scanner sc = new Scanner(file)) {
while (sc.hasNextLine()) {
String[] parodyti = sc.nextLine().split(",");
System.out.println(parodyti[0]);
if (parodyti[0].equals(stopElement)) {
break;
}
}
}
} catch (IOException e) {
System.err.println(e.getMessage());
}
}

Java - parse CSV into Arrays based on columns

I would like to ask for help with this task:
I have CSV for example like this:
column1$column2$column3
123$xyz$321
456$zyx$654
And I would like to parse it by Java to Arrays / Array lists by columns / headers -> for example
ArrayList column1 = [123,456]
ArrayList column2 = [xyz,zyx]
ArrayList column3 = [321,654]
Thanks everyone.
This is how I would have done this..., note the metod to put the columns in another List for less code and to be more dynamic.
public static void main(String[] args) {
ArrayList<ArrayList<String>> columns = new ArrayList<ArrayList<String>>();
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("testing.cvs"));
while ((sCurrentLine = br.readLine()) != null) {
String[] fields = sCurrentLine.split("\\$");
for (int i = 0; i < fields.length; i++) {
if (columns.size()<=i){
columns.add(new ArrayList<String>());
}
columns.get(i).add(fields[i]);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
I thin this can help you to fix the problem just tery it.
public static void main(String[] args) {
Scanner s = null;
try {
s = new Scanner(new File("C:\\temp\\file.txt"));
ArrayList lis1 = new ArrayList();
ArrayList lis2 = new ArrayList();
ArrayList lis3 = new ArrayList();
while (s.hasNext()) {
String d = s.nextLine();
lis1.add(d.split("\\$")[0]);
lis2.add(d.split("\\$")[1]);
lis3.add(d.split("\\$")[2]);
}
for (Object l : lis1) {
System.out.print(l+" ");
}
System.out.print("\n ");
for (Object l : lis2) {
System.out.print(l+" ");
}
System.out.print("\n ");
for (Object l : lis3) {
System.out.print(l+" ");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
you can use the result when you wont

Using FileWriter to print a new line

This is a method to encrypt/decrypt a file(SourceFile.txt) and save the result in another file(ConvertedFile.txt)
private void crypto(int index, int k) throws IOException// 0 -> encrypt 1 -> decrypt
{
FileReader in;
FileWriter out;
try
{
in = new FileReader("SourceFile.txt");
out = new FileWriter("ConvertedFile.txt");
}
catch(FileNotFoundException e)
{
System.out.println("File NOT Found.");
return;
}
c = new cipher(k);
Scanner sc = new Scanner(in);
String line,token;
StringTokenizer st;
while(sc.hasNextLine())
{
line = sc.nextLine();
st = new StringTokenizer(line," ");
while(st.hasMoreTokens())
out.write(c.convert(st.nextToken(),index)+" ");
out.write(10);
}
in.close();
out.close();
}
If the sourceFile has something in it like
Mary had
a little
lamb
The convertedFile contains the encryption as
Qevc leh
e pmxxpi
peqf
Is there anyway how I can use the FileWriter to print a '\n'(new line) at the end of every line?
I even tried the out.write(10)... didn't work
Use PrintWriter
PrintWriter p = new PrintWriter(out);
p.println(str);
You can wrap the FileWriter in a BufferedWriter and use newLine()
BufferedWriter bw = new BufferedWriter(new FileWriter("text.txt"));
bw.write(line);
bw.newLine();
You missed braces of while loop.
while(sc.hasNextLine())
{
line = sc.nextLine();
st = new StringTokenizer(line, " ");
while(st.hasMoreTokens())
{ // Add braces here for newline
out.write(c.convert(st.nextToken(), index) + " ");
out.write(10); //Without braces it will be skipped.
}
}
FileWriter out = null;
try {
out = new FileWriter("F:/work1.txt");
out.write("Rakesh");
out.write("\r\n");
out.write("KR");
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Then the file contains:
Rakesh
KR
Or You Can Use BufferedWriter as
public void fileWrite(String fileName,ArrayList<String> str){
File f ;
FileWriter fw = null;
BufferedWriter bw = null;
try {
f = new File(fileName);
fw = new FileWriter(f.getAbsoluteFile());
bw = new BufferedWriter(fw);
for(String i:str){
bw.write(i);
bw.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(bw!=null)
bw.close();
if(fw!=null)
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Merge Two text files line by line using java

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());
}
}
}

Categories

Resources