Read from textfile to textfield java - java

I have a text file which stores data about a user, from username, password and other details. In the text file, each user's data is stored in one line and separated using ",". I am trying to read from the file and list all the usernames. usernames are first one the line
In the following code, I manage to read and output, but only the last one from the text file. How can I read and output all.
try {
File f = new File("/Users/Nisham/Desktop/javapwd.txt");
Scanner sc = new Scanner(f);
while(sc.hasNextLine()){
String line = sc.nextLine();
String[] details = line.split(",");
String name = details[0];
//int age = Integer.parseInt(details[2]);
jTextArea1.setText(name);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}

Each time through the while loop you reset the text to the newly read input, wiping out the previous text. You need to append the text, not set it.

You are overwriting the text in jTextArea1 in while loop
jTextArea1.setText(name);

Related

How to read certain lines of a txt file in java?

I want to read only the parts i need to. For example my text file look likes these
Name Age Gender
=====================
Donald 13 Male
John 14 Non-binary
Pooh 42 Female
I only want to read the data but i don't know how because my code reads a .txt file line by line
try {
File myObj = new File("database.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) { //to read each line of the file
String data = myReader.nextLine();
String [] array = data.split(" "); //store the words in the file line by line
if(array.length ==5){ // to check if data has all five parameter
people.add(new Person(array[0], array[1],array[2], Double.parseDouble(array[3]), Double.parseDouble(array[4])));
}
}
JOptionPane.showMessageDialog(null, "Successfully Read File","Javank",JOptionPane.INFORMATION_MESSAGE);
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
You can simply call myReader.nextLine() twice before entering your loop to ignore the first two lines.
Another approach you can take is to use a RandomAccessFile object instead of a Scanner to process your input. If you know how many characters are in the file before the beginning of your relevant data, you can use the RandomAccessFile object's seek method to skip to the beginning of your input, e.g. if there are 50 characters in the file before your data you can use randomAccessFile.seek(50) and then read the lines with randomAccessFile.readLine().
I would probably recommend using the first method of skipping 2 lines however because it seems more simple and robust.

Read line by line from text file and save each line to different cell in array

I'm trying to split each line from a text file into cells in an Array. Can I do it with split function and not count the lines in order to create an array?
I am using Scanner for reading files from Scanner. The file contains in each line the following format: number_number
I want to save number_number as a string into a cell in Array.
However, I don't know how many lines in my text file could be, in order to set an array size. I dont want to useLinkedList`, please use the assumption that will not have many lines.
Is it possible to read from file and save each line into cell in array?
There is no problem to change the method from Scanner to another one.
The problem in my code currently that it saves only the first line in my file.
public String[] readFromFileToStringArray(String s) {
Scanner scanner = null;
try {
scanner = new Scanner(new File(s));
} catch (IOException e) {
e.printStackTrace();
}
String[] fileText = null;
if (scanner != null)
while (scanner.hasNext())
fileText = scanner.nextLine().split("\n");
return fileText;
}
When using scanner.nextLine() you read the text until the \n character, so the split you did is pointless since the line string won't have this character.
You can read all the file and then split it:
public String[] readFromFileToStringArray(String s) {
String text = new String(Files.readAllBytes(Paths.get(s)),
StandardCharsets.UTF_8);
return text.split("\n");
}
But really as the other answered said, it would probably be better to simply use List
Should you change the way to add string to the array?
fileText.add(scanner.nextLine());
OR:
List<String> list = new ArrayList<String>(Arrays.asList(fileText));
list.addAll(Arrays.asList(scanner.nextLine().splite("\n")));
String[] fileText = list.toArray();
List<String> lines = Files.readAllLines(pathToFile);
java Files is the easiest way for this.

Reading data from a csv file and storing into an array, my file opens correctly however the file is being read incorrectly

String fileName = "MSFT.csv";
File file = new File(fileName);
try{
Scanner inputStream = new Scanner(file);
while(inputStream.hasNext()){
String data = inputStream.next();
System.out.println(data);
}
inputStream.close();
}
catch(FileNotFoundException e){
e.printStackTrace();
I am attempting to read from a csv file and when I run this code to make sure the file is being read correctly all of the comma separated data displays correctly with the exception of the first line. The first line from the file is being output with each word being on a different line. What am I doing wrong with my initial reading of the file?
An example of my output goes as:
Timestamp,
close,
high,
low,
open,
value,
9:30,57.515,57.57,57.47,57.515,31120
Now all of my words in this case are on the same line in the excel file, but when I run it timestamp, close, high, etc all appear on different lines so I'm not sure why it appears like this.
The Scanner hasNext is defined as follows:
hasNext() Returns true if this scanner has another token in its input.
So when you use it your are reading your csv file token by token and not line by line. Beside that using the Scanner next does the following:
next() Finds and returns the next complete token from this scanner.
And finally using System.out.println will insert a line separator after printing your data, which is why it keeps going to the next line after outputing each token.
Change your code as follows and it should work as expected:
String fileName = "MSFT.csv";
File file = new File(fileName);
try{
Scanner inputStream = new Scanner(file);
while(inputStream.hasNextLine()){
String data = inputStream.nextLine();
System.out.println(data);
}
inputStream.close();
} catch(FileNotFoundException e){
e.printStackTrace();

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.

I want to parse multiple strings into variables from a .txt file in java. What's the easiest way to do it?

What's the best way to do it? Should I use the File class and scanner? I've never done it before and can't seem to find a solid guide for it online so I figured I would ask here.
Edit:
The text file I am parsing is 3 columns, the first three are ID NAME BIRTHDATE then actual data.
Edit (code from pastie):
public void readFromFile(File file )
{
try
{
System.out.println("success..");
s = new Scanner(file);
BufferedReader input = new BufferedReader(new FileReader(file));
String jj = null;
while((jj = input.readLine())!=null)
{
String [] words = jj.split("\\t");
String name = "";
String id = "";
String birthdate ="";
for (int i = 3; i<words.length; i+=3)
{
id =words[i];
name = words[i+1];
birthdate=words[i+2];
Person p = new Person(id, name, birthdate);
peopleMap.put(p.id,p);
names.add(p);
System.out.println("New entry added to file: "+name+"\\t"+"ID: "
+id+"\\t"+"Birthdate"+birthdate);
}
}
}
catch(IOException e)
{
}
}
The easiest way depends on the format of the text file. From your other comment, it sounds like the lines are tab separated values. As a beginner you will probably find it simplest to use Scanner. Specifically, Scanner.nextLine(). Couple that with using String.split("\t") to split the data into an array (assuming the format is tab-separated-values).
Simply depends on the format of the text file.
If its simple name value pair then you can use java.util.Properties. for example a.properties could look like:
name=john
city=san jose
date=12 july 2010
then you can load this as:
Properties props = new Properties();
props.load(new FileInputStream("a.properties"));
If format is different than what is supported by java.util.Properties.load() then using java.util.Scanner would be helpful to process it line by line:
File file = new File("data.txt");
try
{
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
//Process each line seperately
processLine(line);
}
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
If you are free to say what the syntax / structure of the text file is, then consider making it a Java properties file. Then you can load and save the file with minimal programming effort using the java.util.Properties class.
This is what I like to do in that situation:
Scanner s = new Scanner(file);
Scanner line;
String name;
String date;
int id;
while(s.hasNext()){
line = new Scanner(s.nextLine());
id = line.nextInt();
name = line.next/*String*/();
date = line.next/*String*/();
/* Do something with id, name and date */
}
Maybe there is some exception handling or something like that
(Anyone want to comment on the efficiency of creating many new Scanners?)

Categories