Read data from file into an array Java [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
In my program, I am asking users for input for a subject name and a subject code which i pass through to a subjects.txt file eg:
Inside the TestSubject class -
//ask the user to input a subject name
System.out.println("Please enter a Subject Name");
//assign each input to a side
String subjectName = input.nextLine();
//ask the user to input a subject code
System.out.println("Please enter a Subject Code");
String subjectCode = input.nextLine();
//add records to the file
subject.addRecords(subjectName, subjectCode);
Inside the subject class -
//add the records of valid subject name and subject code
public void addRecords(String name, String code) {
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("subjects.txt", true)))) {
out.printf(name);
out.printf("\n");
out.printf(code);
out.printf("\n");
out.close();
}catch (IOException e) {
}
}
I then want to read this file and pass the data through to an arraylist. The file might look something like:
Testing 1
ABC123
Testing 2
DEF456
Testing3
GHI789
I want to pass it through to an arraylist so then I can then process other methods against this array such as sorting, see if any are the same etc.
//read data from subjects file and place in an array
public void readData(){
Scanner input = new Scanner("subjects.txt");
while (input.hasNext()) {
String subjectName = input.nextLine();
String subjectCode = input.nextLine();
}
ArrayList<String> subjectNames = new ArrayList<String>();
ArrayList<String> subjectCodes = new ArrayList<String>();
//add the input to the arrays
subjectNames.add(subjectName);
subjectNames.add(subjectCode);
//display the contents of the array
System.out.println(subjectNames.toString());
System.out.println(subjectCodes.toString());
}
Even if there is a good tutorial around that I might be able to be pointed in the right direction...

Thanks for editing your post. Much easier to help when I can see what's causing problems.
You're checking hasNext() once every two lines. Should be checked every line because you shouldn't trust the text file to be what you expect and should display an informative error message when it isn't.
You're also declaring the strings inside the scope of the loop so nothing outside the loop even knows what they are. Shoving subjectCode into into the subjectNames collection is probably not what you want. As it is, each nextline() is stepping on the last string value. That means you're forgetting all the work done in previous iterations of the loop.
The collections.add() calls, not the strings, should be in the loop. Make sure to declare the collections before the loop and put their add calls in the loop. See if you get useful results.
Give "Reading a plain text file in Java" a read.

Regarding your tutorial query, I often find some good basic examples on this site including one for reading from a file as referenced in the link. Using the main principles of that example here is one way you could try and read the lines from your file:
public static void main(String[] args){
ArrayList<String> subjectNames = new ArrayList<String>();
ArrayList<String> subjectCodes = new ArrayList<String>();
//Path leading to the text file
Path data = Paths.get(System.getProperty("user.home"), "Desktop", "file.txt");
int count = 0;//Will indicate which list to add the current line to
//Create a buffered reader to read in the lines of the file
try(BufferedReader reader = new BufferedReader(new FileReader(data.toFile()))){
String line = "";
while((line = reader.readLine()) != null){//This statement reads each line until null indicating end of file
count++;//Increment number changing from odd to even or vice versa
if(count % 2 == 0){//If number is even then add to subject codes
subjectCodes.add(line);
} else {//Otherwise add to subject names
subjectNames.add(line);
}
}
} catch (IOException io){
System.out.println("IO Error: " + io.getMessage());
}
System.out.println("Codes: ");
display(subjectCodes);
System.out.println("\nNames: ");
display(subjectNames);
}
private static void display(Collection<String> c){
for(String s :c){
System.out.println(s);
}
Hope it helps!

Related

How would I write this code to make it read a file that has an unknown amount of lines? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Process_TCPProbe_dm{
public static void main(String[] args) throws IOException {
//Extracting the port numbers from the file names passed in the arguments
String portNumber1 = args[1].substring(9, 14);
String portNumber2 = args[2].substring(9, 14);
String portNumber3 = args[3].substring(9, 14);
int i = 0;
Scanner s = new Scanner(new FileReader(args[0]));
//Initialising array of contents with length equals to number of lines in the input file
String[] contents = new String[18];
while(true)
{
if (i == 18)
break;//Skipping the last line of the file
//Replaces the whitespace with comma and stores in the string array
contents[i] = s.nextLine().replace(" ", ",");
i++;
}
BufferedWriter bw1 = new BufferedWriter(new FileWriter(args[1]));
BufferedWriter bw2 = new BufferedWriter(new FileWriter(args[2]));
BufferedWriter bw3 = new BufferedWriter(new FileWriter(args[3]));
//Iterating the array of contents using a for each loop
for(String each:contents)
{
//Writing the string to the corresponding file which matches with the portNumber
//along with a new line
if (each.contains(portNumber1))
{
bw1.write(each);
bw1.newLine();
}
else if(each.contains(portNumber2))
{
bw2.write(each);
bw2.newLine();
}
else if(each.contains(portNumber3))
{
bw3.write(each);
bw3.newLine();
}
}
//This is necessary to finally output the text from the buffer to the corresponding file
bw1.flush();
bw2.flush();
bw3.flush();
//Closing all the file reading and writing handles
bw1.close();
bw2.close();
bw3.close();
s.close();
}
}
Here is my code, however, it only reads a file the size of 19 lines. I know i could use an ArrayList, but I'm not exactly sure how to go about it. I hope my question makes sense. If it'll help you understand better ill put the purpose of the code below.
This image is of the instructions for what the code is written for. It might just be extra information, but I put it here in case it'll better help to explain my question.
Just replace your array with Array Lins like this ArrayList<String> list = new List<>(); and then replace contents[i] = s.nextLine().replace(" ", ",");with list.add(s.nextLine().replace(" ", ","));. After this you will not need counter "i" anymore and break you loop in if condition. Just add scanner.hasNext() in a while condition.
Your looping condition should be based on Scanner.hasNextLine and you don't need the variable i. Use an ArrayList to score an unknown amount of elements.
Scanner s = new Scanner(new FileReader(args[0]));
final List<String> contents = new ArrayList<>();
while(s.hasNextLine()){
contents.add(s.nextLine().replace(" ", ","));
}
This can be shortened using Files.lines. Note that this throws an IOException that you will need to handle.
final List<String> contents = Files.lines(Paths.get(args[0]))
.map(s->s.replace(" ", ",")).collect(Collectors.toList());

How should I assign some values from a txt file to an array in Java? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I just started to learn Java. As the title says... I would like to know how should I assign some values from a txt files to an array in Java to work with them (for example to sort them).
For example in C++:
#include<fstream>
using namespace std;
int v[10];
int main()
{
ifstream fin("num.txt");
int i;
for(i=0;i<10;i++)
fin>>v[i];
}
Right guys. Thank you for all the information. I see that is a little bit more complicated than C++, but I'll learn this. Furthermore, when I was intern at a small company I saw that the employees there made a code which scanns an XML files. I guess it's much more complicated, but that's fine. :)
If each line of the file is an integer then:
List<Integer> results = new ArrayList<Integer>();
try
{
File myFile = new File("./num.txt");
Scanner scanner = new Scanner(myFile);
while (scanner.hasNextInt())
{
results.add(scanner.nextInt());
}
}
catch (FileNotFoundException e)
{
// Error handling
}
https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=read%20text%20file%20java
I believe this might help you find a solution.
Alright, getting that trolling out of the way.
PSEUDO CODE:
while not end of file
get next line
put next line in a Array List
Remember each line is a String you can parse strings with .split() to get all the words from the file or use some REGEX magic.
EDIT:
Ok I saw the other anwser and scanner.nextInt() makes me cringe. I had to show an actual code implementation. Using a REGEX to denot the pattern, is a farm more superior method. You can be reading garbage data for all you know! Even if REGEX is beyond you at the moment they are so freaking useful it's important to learn the correct method to do something.
List<Integer> list = new ArrayList<Integer>();
BufferedReader reader = new BufferedReader(new FileReader("/path/to/file.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
if(line.matches("[\\s\\d]+"){
String[] temp = line.split(" ");
for(int i = 0; i < temp.length; i++){
list.add(Integer.parseInt(temp[i]));
}
}
}
The following program will read each character in the file to an ArrayList. In this example white spaces are loaded into the ArrayList, so if this is not intended you have to work some aditional logic :)
If the intention is to fill the array with words instead of characters, make a StringBuilder and inside the loop replace the logic with sb.append(new String(buffer));
Then, as progenhard suggested, use the split() method on the returning String from StringBuilder;
public class ReadFile {
public static void main(String[] args){
FileInputStream is = null;
try{
File file = new File("src/example/text");
is = new FileInputStream(file);
byte[] buffer = new byte[10];
List<Character> charArray = new ArrayList<Character>();
while(is.read(buffer) >=0){
for(int i=0;i < buffer.length;i++)
charArray.add((char)buffer[i]);
//Used remove the assigned values on buffer for the next iteration
Arrays.fill(buffer, (byte) 0);
}
for(char character : charArray){
System.out.println(character);
}
}catch(IOException e){
System.out.println("Something wrong with the file: " + e);
}finally{
if(is != null){
try {
is.close();
} catch (IOException e) {
System.out.println("Something wrong when closing the stream: " + e);
}
}
}
}
}

File overwriting/reading advice required [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
recently have gone to test a form of key validation code from files in Java. I'm still new to this(IO) and looking online brings endless methods of approaching this but I'm not capable of distinguishing the various pros & cons between these methods. I would like to present my code and ask me how I should tackle in properly, it works but I'm not all too satisfied.
I know most of you are against advice-oriented questions and if it is the case I'll gladly put the topic down, just wanted to ask for some help beforehand. Thank you
/*
* To be able to give you a rundown of the situation:
* Inside my project file I have a .txt file named 'MasterKey'
* Initially inside this file is a key and validation boolean 'false'
* On start-up the program analyzes this file, if it detecs a key it then
* Asks the user to input the key. If it is valid it then creates/overwrites the
* Previous file with a new .txt with same name but only "true" is inside it.
* If the key is incorrect, it will continue requesting for the key
*/
import java.io.*;
import java.util.Scanner;
public class MasterKeyValidationTest {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
getFileInfo(); //Method below
}
private static void getFileInfo(){
File readFile = new File("/Users/Juxhin's Lab/Desktop/Projects/MasterKey.txt"); //My file directory
try{
BufferedReader getInfo = new BufferedReader(
new FileReader(readFile));
String fileInfo = getInfo.readLine(); //Gets the key or 'true'
if(fileInfo.contains("true")){ //If file contains 'true', program is valid
System.out.println("Valid");
}else{
System.out.println("Enter Key");
String key = input.next(); //Receive input for the key
if(!fileInfo.contains(key)) { //If the file doesn't contain the key you just entered
System.out.println("Invalid key");
key = input.next(); //Receive another key input
getFileInfo(); //Start the method from top again to check
}
if (fileInfo.contains(key)) { //If the file contains the key you just entered
System.out.println("Program valid");
FileWriter fstream = new FileWriter("/Users/Juxhin's Lab/Desktop/Projects/MasterKey.txt"); //Create/Overwrite the MasterKey.txt file
BufferedWriter out = new BufferedWriter(fstream);
out.write("true"); //Input "true" inside the new file
out.close(); //Close the stream
}
}
}catch(FileNotFoundException e){
System.out.println("File not found");
System.exit(0);
}catch(IOException e){
System.out.println("An IO Error");
System.exit(0);
}
}
}
Some advice ..
1. String fileInfo = getInfo.readLine(); //Gets the key or 'true' .. reads only 1 line (if that is what you want..)
2. use fileInfo =fileInfo.trim() // to remove leading and trailing whitespaces.
3. If you just want to "read" the file, use FileReader, BufferedReader. If you want to "parse" the file, use a Scanner.

On parsing a CSV file [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have this project for the university where they're asking me to create a simple bank system in Java. So far I've been able to do well except when it comes to store data for using it next time..
Lately I've found the storing code where all of my data are stored on a text file as :
int str str int
5487,Samer,Lebanon,1000000
8792,Ahmad,Lebanon,2500000
and so on using the io libraries such as :
public static void saveToFile(int[] accounts,String[] names,String[] addresses,int[] balances,int maxTmp) {
bubbleSorting(accounts,names,addresses,balances,maxTmp);
try {
//What ever the file path is.
File statText = new File("C:/Users/Wicked Angel/Desktop/customers.txt");
FileOutputStream is = new FileOutputStream(statText);
OutputStreamWriter osw = new OutputStreamWriter(is);
Writer w = new BufferedWriter(osw);
for(int i=0;i<maxTmp;i++)
w.write(accounts[i] + "," + names[i] + "," + addresses[i] + "," + balances[i] + System.getProperty("line.separator"));
w.close();
} catch (IOException e) {
System.err.println("Problem writing to the file customers.txt");
}
}
The difficulty is when I'm trying to import that text file and set each value to its specific array..
Any help ?
First, you have to read the text file line by line
// your file
File statText = new File("C:/Users/Wicked Angel/Desktop/customers.txt");
// read file using FileReader class
FileReader fr = new FileReader(statText);
BufferedReader br = new BufferedReader(fr);
// the first line is the header line and might be ignored
String line = br.readLine();
// loop through each line by reading it from the buffer
while ((line = br.readLine()) != null) {
// process each line
}
br.close();
This will loop through each lines in your file. The line will be a string. Here below is an example of the first string in the while loop.
line: "5487,Samer,Lebanon,1000000"
What you have to do is to separate each parts and bring it to an array. This can be done with the Split() method from String-object. (click on the method name to read the documentation).
String[] myParts = line.Split(",");
The result will be then
myParts: ["5487"] ["Samer"] ["Lebanon"] ["1000000"]
That's an array. Just go through the above array and store each variable in the appropriate array. The first element in ArrayList<int> accounts, the second element in ArrayList<String> names ... Here below is an example for the first element
// outside loop
ArrayList<int> accounts = new ArrayList<int>();
// inside loop
accounts.Add(Integer.parseInt(myParts(0)));
// since it should be an integer, I parse it to int before adding it
The reason behind the use of ArrayList is because you don't know how many lines you have in your text. Ofc you can check it, but performance wise, it's advisable to use a dynamic array, which is ArrayList. (Or other list objects if you want). If you want to read more about ArrayList, please refer to this documentation to create, add element, get element, ...
Oh, also don't forget to cast the first and third element to int, or you will get errors when trying to add these info in an int ArrayList. If you want, you can also validate each element to ensure that you don't have faulty data (like the result of splitting a line is an array of three elements, which is incorrect).
This should help you to solve your import problems. Good luck
use your ',' as the delimiter. read each line and seperate them using delimiter like, say if i wanted to extract String text="holy,molly" i would do
String holy=text.substring(0,text.indexOf(','));
and
String molly=text.substring(text.indexOf(','))

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