Converting text dumped in textfile to Csv and Array - java

i have been using an actionListenerto pass text from numerous TextFields into a text file named writetouser.txtthis works fine though i have noticed that this text is just dumped and is not in the format of an array. For the purposes of this application it is necessary that i am able to search this text file and show values based on searches entered. I have a file which reads the data from the text file and have attempted to convert the data to CSV's so it is is readable as an array. i am wondering what must be entered instead of user, pass in order to take the text from inside the filewritetouser.txt.
Addendum:
public void ReadUser()
{
try{
// Open the file
FileInputStream fstream = new FileInputStream("writetouser.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
//System.out.println (strLine);
String[] items = strLine.split(",");
String[][] usersArray = new String [10][2];
for (String item : items) {
System.out.println(item);
}
}
//Close the input stream
in.close();
}catch (Exception e){
//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
here is an example of the data which i am trying to separate. it is entered into textfile as
inputUser = user + ", " + pass;
writetouser.WriteToUser(inputUser);
dburgess, 2345

I think what you want is:
String[] items = strLine.split(",");

I notice that this line is commented out:
//System.out.println (strLine);
Which suggests to me that you were probably trying to ensure that you're getting the line you expect from your file. If you are getting what you expect, we're clear to move on. If not, there's a problem in how the file is being read, or the data isn't formatted how you expect.
If we're good so far, we've arrived at the problem of parsing and displaying the content of the file. I'm assuming that you're trying to write the contents of the file to your terminal and expecting one format, but getting another.
I think what you'll see right now is something like this:
Username: dburgess
Password: 2345
(with no more than 1 username/password pair printed).
And I'm guessing you want something like this:
Username: dburgess Password: 2345
Username: someOtherUser Password: SomeOtherpass
Username: blahblah Password: etcPass
....
Username: thelastOne Password: Icanhazpassword?
There are a lot of assumptions there (I'm still not entirely sure what you're trying to do) -- if those assumptions are correct, let me know; I'll post some formatting tips.

Upon reviewing my code i noticed that the two pieces of code below were doing the exact same thing which is why i was being presented with each piece of info twice.
A
for (String item : items) {...}
B
for (int i = 0; i < items.length; i++) {
String item = items[i];
....
}

Related

Java read from file line by line not reading lines correctly

I've saved a good few tweets in a text file with the following format:
Country:Brazil_result.txt Date: \r\n09/19/14 TweetTextExtract: #Brazil on track to becoming the leader of #wind #energy production in Latin America http://t.co/MFJjNPxodf
Country:Brazil_result.txt Date: \r\n09/19/14 TweetTextExtract: #ConceptOfficial FOLLOW ME GUYS PLEASE I LOVE YOU SO MUCH 💕BRAZIL LOVE YOU💙💚💛x16
Country:Brazil_result.txt Date: \r\n09/19/14 TweetTextExtract: #JamesFenn90 plenty teams travelled far more in Brazil from their bases to each game.I'm sure eng can manage a trip to Amsterdam etc etc
Now what I look to do is read in line by line from the text file and then split the line by "TweetTextExtract: " but for some reason I keep getting an ArrayIndexOutOfBoundsException:1 error and I can't see why as every line has the "TweetTextExtract: " term. Here is the error in the console:
Country:Brazil_result.txt Date: \r\n09/19/14 #ConceptOfficial FOLLOW ME GUYS
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at WhatToThink.main(WhatToThink.java:28)
The line with this tweet has the "TweetTextExtract: " term and so does the line succeeding it. I'm not to sure why this is breaking. Here is the code:
String folderPath = "C:/Users/me/workspace/Sentiment Analysis/Good Data";
File fin = new File(folderPath + "/Brazil_result" + ".txt");
FileInputStream fis = new FileInputStream(fin);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line = null;
while ((line = br.readLine()) != null) {
String[] stringline = line.split("TweetTextExtract: ");
System.out.println(stringline[0] + stringline[1]);
//System.out.println(line);
}
br.close();
Your problem is almost surely a bad text encoding for your file. Save your file as UTF-8 (or UTF-16), then use
new InputStreamReader(fis, "UTF-8") //or UTF-16
If the encoding you use in the above constructor does not match the one of the text file, you will get gibberish and then the split won't work even on the first line.
If you want to keep the original encoding for you text file, just find out what it is and use it instead.
it actually doesn't give the exception for me when i run it.but how ever you can avoid this error by dynamically print element inside splited String.the following enhanced loop will gives you the same result ..
String[] stringline = line.split("TweetTextExtract: ");
for (String s : stringline) {
System.out.print(s);
}
System.out.println("");
and you can find your self how much element exist inside the stringline array by looking at the result.
You can use something like that:
if (line.contains("TweetTextExtract: ")){
String[] stringline = line.split("TweetTextExtract: ");
System.out.println(stringline[0] + stringline[1]);
}
else{
System.out.println("Line doesn't't contain \"TweetTextExtract: \"");
}

How do I add lines (read from a .txt) separated by AN ENTER KEY (in .txt) into separate elements of string arrayList?

I'm reading .txt file into my program and am adding lines of the .txt into a String arrayList. How do I add lines DELINEATED BY AN ENTER KEY (in .txt) into separate elements of the arrayList? Right now if I had the following written in text:
this is a test
test
test test
It would output:
this is a testtesttest test
What I want it to do is read things on a per line basis, and put it into different elements of the stringArrayList. So I want "this is a test" to be an element, and "test", and then finally "test test".
My code is really ugly, but right now all I want to do is get it to work for my purpose. My first purpose is getting to read a .txt by line. My second purpose is going to be parsing an element for a particular substring (a URL), connecting that URL to the internet, and then comparing a part of that page source of the webpage (parsing for a particular keyword) to the line ABOVE the substring I desire. But that's a question for another time :^)
import java.io.*;
import java.util.*;
public class Test {
public static void main(String [] args) {
// The name of the file to open.
String fileName = "test.txt";
List<String> listA = new ArrayList<String>();
// This will reference one line at a time
String line = null;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
listA.add(line);
//*** THIS IS WHERE THE MAGIC HAPPENS ***\\ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
}
// Always close files.
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open da file ofheee hah. '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
System.out.println();
System.out.println("array FOr loop thingy incoming:");
System.out.println();
for (int i = 0; i < listA.size(); i++) {
System.out.print((listA.get(i)).toString());
}
}
}
You just have to use println instead of print:
System.out.println((listA.get(i)).toString());
Alternatively, you can add the line break character \n
Your code seems to be working so far. If you just want to see what elements are in listA, just print it out:
System.out.println(listA);
Output:
[this is a test, , test, , test test, ]
Note that the extra lines in your input file are also being stored in listA. I'm not sure if that's the behavior you want.

Searching a text file and printing Java

Im trying to search a csv file for a specific string. I want to print out all entries in the csv that have a specific module in the line in the csv but I cant seem to get it working. Also is it possible to print out the out in one JOptionPane window instead of a different window for every result.
Csv format
12175466, C98754, B
12141895, CS4054, B
12484665, CS3054, B
18446876, CS1044, B
User Input: CS4054
Desired Results: 12141895, CS4054, B
public static void DisplayResults() throws IOException
{
String line;
String stringToSearch = JOptionPane.showInputDialog(null, "Enter the module code ");
BufferedReader in = new BufferedReader( new FileReader("StudentResults.csv" ) );
line = in.readLine();
while (line != null)
{
if (line.startsWith(stringToSearch))
{
JOptionPane.showMessageDialog(null, line );
}
line = in.readLine();
}
in.close();
Do you mean to use startswith? Maybe try contains.
How about this?
String theAnswer="";
if (line.contains(stringToSearch)) {
theAnswer += line +"\n";
}
JOptionPane.showMessageDialog(null, theAnswer);
Your CSV file has a specific format: Values separated by a comma. So you can split each line into an array and check the second value.
String[] values = line.split(",");
if(values[1].trim().equals(stringToSearch))
JOptionPane.showMessageDialog(null, line );
EDIT:
Use the above code, when you're sure, the user always types in the second value. If you want to search over all entries use this:
for (String val : values)
if(val.trim().equals(userInput))
JOptionPane.showMessageDialog(null, line );

Search a text document for a line - JAVA

I am trying to make a login screen that can read the usernames and passwords from a text file. I have already built the registration page which outputs the username and password to a file by executing the following:
try (BufferedWriter out = new BufferedWriter(fstream)) {
try {
out.write(username + " " + password);
out.newLine();
JOptionPane.showMessageDialog(null,"User Account '" + username + "' Created");
} catch (IOException ex) {
Logger.getLogger(ServerMenu.class.getName()).log(Level.SEVERE, null, ex);
}
}
the text file will looking something like this:
user1 password1
user2 password2
I have been reading through a lot of documentation to try and figure this one out however the more reading i do the more confused I get. The reason why I am doing it in this way is so that I can continue reading and writing to .dat files for the information that the system will eventually hold.
If anybody can help me in any way shape of form that would be amazing!
Thanks
C
Quick and easy solution. Each line is commented but if you need any help or if there's anything you don't get please let know.
import java.io.*;
class FileRead
{
public static boolean main(String lineToCompare)
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
//Compare the line with the line to compare (string)
if(strLine.compareTo(lineToCompare) == 0)
return true;
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
return false;
}
}
I am really not sure whether you want to execute the above code for a specific username and password, or all of them.
If you want to get specific line from the file, and you already have access to the offset of the line you want to read, you can use RandomAccessFile. This class lets you move the file pointer to a certain position, and then you can simply read the next line to get username and password.
However, if you want to read a specific line but have no information where that line could be in the input file, you will need to read each line (eg., using a BufferedReader) to find the one you need. You can also take this approach, if you want to read the files line by line.

Java - Use Scanner to read big text files

I have a very big text file with customer information. I would like to read all the customer information from the text file.
This is how my text file is organized:
Costomer 1:
Name:
Erik Andersson
Adress:
Street1
Phone number:
085610540
Costomer 2:
Name:
Lars Larsson
Adress:
Street1
Phone number:
085610540
I would like to be able read all the customer information. Is there any good way to it with? I have read about Scanner and Pattern and was wondering if it is good idea to use them in this case? My text file is very big and contains hundreds of customers.
Dose any one have any idea how I could read all the information from the text file? I have created a class with customer variabled, I only need help with the reading from the text file. I want to read the information in an organized way.
All help is very very appreciated.
Like so:
public void getEmployees(File f) throws Exception {
// An ArrayList of your Employee-Object to hold multiple Employees
ArrayList<Employee> employees = new ArrayList<Employee>();
// The reader to read from your File
BufferedReader in = new BufferedReader(new FileReader(f.getAbsolutePath()));
// This will later contain one single line from your file
String line = "";
// Temporary fields for the constructor of your Employee-class
int number;
String name;
String adress;
String phone;
// Read the File untill the end is reached (when "readLine()" returns "null")
// the "line"-String contains one single line from your file.
while ( (line = in.readLine()) != null ) {
// See if your Line contains the Customers ID:
if (line.startsWith("Customer")) {
// Parse the number to an "int" because the read value
// is a String.
number = Integer.parseInt(s.substring("Customer ".length()).substring(0,s.indexOf(':')));
} else if (line.startsWith("Adress:")) {
// The Adress is noted in the next line, so we
// read the next line:
adress = in.readLine();
} else if (line.startsWith("Phone number:")) {
// Same as the Adress:
phone = in.readLine();
} else if (line.startsWith("Name:")){
// Same as the Adress:
name = in.readLine();
} else if ( line.equals("") ){
// The empty line marks the end of one set of Data
// Now we can create your Employee-Object with the
// read values:
employees.add(new Employee(number,name,adress,phone));
}
}
// After we processed the whole file, we return the Employee-Array
Employee[] emplyeeArray = (Employee[])employees.toArray();
}
Please give +1 and correct for ur hw lol
As a little extension to stas answer:
The originally posted code doesn't work, because a continue skips the current loop-iteration. So unless the line starts with "", nothing is ever done.

Categories