Java: Using File & Buffered Reader to fill an Array - java

So, I have my first Java project due in my new course this Sunday. One of the (most important) things we need to do is to fill 2 arrays with information read from a file. My professor said to use a file and buffered reader to do this.
Unfortunately, I've never used either.
For the first array I need to: Create a String array with 15 elements, then Read the state search data from the data file and store each item into the array.
The filename is 'states.search.txt' and contains the following.
California
Texas
AK
California
Indiana
Missippi
Jacksonville
Okalahooma
Florida
Maine
Hawaii
Puerto_Rico
FL
New_York
Auburn
The 2nd array is a lot more involved, so I'll ask separately for that one.
All help is appreciated!

You can read lines from file follow:
public static void main(String args[]) {
try {
List<String> states = new ArrayList(15)<>; // ArrayList is superstructure over array
FileInputStream fstream = new FileInputStream("C:\\states.search.txt");
String state;
while ((state = br.readLine()) != null) {
states.add(state);
}
in.close();
} catch (Exception e){
e.printStackTrace();
}
}
}
But you have to turn on your brain to do your home work, it's better for you.

Related

Need help creating a program to read in entries and replace existing entry if there is one for that date

I am very new to coding and learning java, I can picture what the program needs to do however implementing to code has proven tough for me. I am trying to create a constructor. The constructor needs to do the following-
Constructor: When reading in and storing the individual quiz data, you will need to watch out for repeated quizzes. If a quiz is read in with a date that already has an entry stored, you will need to replace the earlier entry with the new one. I have been provided a java doc for this, however I will need to create the code. I have attached an image of the javadoc as well as the code that I currently have.
Javadoc for Constructor
public QuizList(String filename)
{
this.quizzesList = 0;
this.quizList = new ArrayList<Quiz>();
try {
Scanner infile = new Scanner(new File(filename));
while (infile.hasNextLine()){
String quizDate = infile.next();
String pointsEarned = infile.next();
String possiblePoints = infile.nextLine().trim();
Quiz quiz = new Quiz(quizDate, points, possible);
this.quizzes.add(quiz);
}
infile.close();
}
catch (java.io.FileNotFoundException e) {
System.out.println("No such file: " + filename);
}
File has lastModified method: https://docs.oracle.com/javase/8/docs/api/java/io/File.html.
I recommend you to iterate the files on the directory and check their last modified date.

Reading file containing random numbers, sorting it and than writing to other file

In an interview I was asked the following question,
There is a file named sourceFile.txt containing random numbers aligned one below other like below,
608492
213420
23305
255572
64167
144737
81122
374768
535077
866831
496153
497059
931322
same number can occur more than once. The size of sourceFile.txt is around 65GB.
I need to read that file and write the numbers into new file lets say destinationFile.txt in sorted order.
I wrote the following code for this,
/*
Copy the numbers present in the file, store in
list, sort it and than write into another file.
*/
public static void readFileThanWrite(String sourceFileName,String destinationFileName) throws Exception{
String line = null;
BufferedReader reader = new BufferedReader(new FileReader(sourceFileName));
List<Integer> list = new ArrayList<Integer>();
do{
if(line != null){
list.add(Integer.parseInt(line));
}
line = reader.readLine();
}while(line != null);
Collections.sort(list);
File file = new File(destinationFileName);
FileWriter fileWriter = new FileWriter(file,true); // 'True' means write content to end of file
BufferedWriter buff = new BufferedWriter(fileWriter);
PrintWriter out = new PrintWriter(buff);
for(Iterator<Integer> itr = list.iterator();itr.hasNext();){
out.println(itr.next());
}
out.close();
buff.close();
fileWriter.close();
}
But the interviewer said the above program will fail to load and sort numbers as the file is large.
What should be the better solution ?
If you know that all the numbers are relatively small, keeping an array of occurences would do just fine.
If you don't have any information about the input, you're looking for external sorting. Here's a Java project that could help you, and here is the corresponding class.

Java read .txt file with array and save

Ok this is quite a long one but I've looked everywhere and I'm still unsure on how to do it. This is a list of students information in the classroom layout. The program is used to let a child choose a seat but once they have chose it then it should have a status update so nobody else can take it.
Columns explained - (1)Student in number order (2)Male/Female (3)Window Seat/Aisle Seat (4)With/Without table (5)Forward Seat/Backward Seat (6) Ease of Access Seat
.txt file;
01 2 true false true false
02 2 false false true false
03 1 true false true true
04 2 false false true true
05 1 true true true false
I understand they don't totally make sense but it's just an example.
How do I get the program to read through each one of these rows using an array to store all this information? for child 1,2,3's seat etc. The .txt file represents exactly what kind of seat it is as explained above. Once the array has read through I want it to be able to save each row.
If you just want to read a file and store each line seperately in an array you can do the following. Note that it's not possible to create the array beforehand as you do not know how many lines you will get.
String[] result;
ArrayList<String> lines = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader("path"))) {
while (reader.ready()) {
lines.add(reader.readLine());
}
} catch (IOException e) {
// proper error handling
}
result = lines.toArray(new String[lines.size()]);
Or if you want to be able to access the columns directly:
String[][] result;
ArrayList<String[]> lines = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader("path"))) {
while (reader.ready()) {
lines.add(reader.readLine().split(" ");
}
} catch (IOException e) {
// proper error handling
}
result = lines.toArray(new String[lines.size()][]);
for(String[] lineTokens) {
String studendNumber = lineTokens[0];
boolean gender = Boolean.parseBoolean(lineTokens[1]);
...
}
let's say your file name is students.txt
all u need to do is read the data and store it into an array of strings to deeal with it later so her's the stuff :
BufferedReader in = new BufferedReader(new FileReader("students.txt"));
String[][] data = new String[][6];
int i = 0;
while(in.ready()){
data[i] = bf.readLine().split(" ");//use whatever is separating the data
i++;
}
If you just want to read a text file in java, have a look at this: Reading a plain text file in Java
A saving of each row won't be possibe, it's a file, not a database. So load the file, change the data as you like, save it.
You should also think about the format... may be use XML, JSON or CSV format to store the data. There are libs which do most of the job for you...
If you are planning parallel access to your program data (more than one program instance and users, only one datafile), a simple text file is the wrong solution for your needs.

Populating ArrayList from file without including formatting info and back-slashes

To start, no this is not a homework assignment. I am fresh out of highschool and am trying to do some personal projects before college. I've been trying to populate an ArrayList with elements from a document. The document looks like:
item1
item2
item3
...
itemN
After failing many times on my own, I tried different solutions from this website. Most recently, this one got me the closest to what I desire:
public static void main(String[] args) throws IOException {
List<String> names = new ArrayList<String>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("/Users/MyName/Desktop/names.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
names.add(line);
}
} finally {
reader.close();
}
for(int i = 0; i<names.size(); i++){
System.out.println(names.get(i));
}
//String[] array = (String[]) names.toArray(); Not necessary that it is in an array
}
The only problem is that this returns something rather ugly in the console:
{\rtf1\ansi\ansicpg1252\cocoartf1347\cocoasubrtf570
{\fonttbl\f0\froman\fcharset0 Times-Roman;}
{\colortbl;\red255\green255\blue255;}
\margl1440\margr1440\vieww10800\viewh8400\viewkind0
\pard\tx577\tx1155\tx1733\tx2311\tx2889\tx3467\tx4045\tx4623\tx5201\tx5779\tx6357\tx6935\tx7513\tx8091\tx8669\tx9247\tx9825\tx10403\tx10981\tx11559\tx12137\tx12715\tx13293\tx13871\tx14449\tx15027\tx15605\tx16183\tx16761\tx17339\tx17917\tx18495\tx19072\tx19650\tx20228\tx20806\tx21384\tx21962\tx22540\tx23118\tx23696\tx24274\tx24852\tx25430\tx26008\tx26586\tx27164\tx27742\tx28320\tx28898\tx29476\tx30054\tx30632\tx31210\tx31788\tx32366\tx32944\tx33522\tx34100\tx34678\tx35256\tx35834\tx36412\tx36990\tx37567\tx38145\tx38723\tx39301\tx39879\tx40457\tx41035\tx41613\tx42191\tx42769\tx43347\tx43925\tx44503\tx45081\tx45659\tx46237\tx46815\tx47393\tx47971\tx48549\tx49127\tx49705\tx50283\tx50861\tx51439\tx52017\tx52595\tx53173\tx53751\tx54329\tx54907\tx55485\tx56062\tx56640\tx57218\tx57796\li577\fi-578
\f0\fs24 \cf0 \CocoaLigature0 item1\
item2\
item3\
...
itemN\
}
How can i get it to read from the file but not include all of the back-slashes and formatting info?
you just need to really save the file as text file. Your file looks like an RTF file at the moment. Open Pages application and open that file. Go to File... Export to... Plain Text... and save it into a new file.
Looks like your names.txt file got saved as RTF (Rich Text Format). Make sure you convert it to plain text.

Read the five score in a textfile then print them back with the new score added to the list - ANDROID

In my program when the player submits a score it gets added to a local text file called localHighScores. This is list of the top five score the player has achieved while on that specific device.
I wasn't sure how to write to a new line using FileOutputStream (if you know please share), so instead I've inputted a space in between each score. Therefore what I am trying to do is when the player clicks submit the program will open the file and read any current data is saved. It will save it to an String Array, each element being one of the five score in the text file and when it hits a 'space' in the fie it will add the score just read to the write array element
The code I currently have is as follows:
String space = " ";
String currentScoreSaved;
String[] score = new String[5];
int i = 0;
try
{
BufferedReader inputReader = new BufferedReader(new InputStreamReader(openFileInput("localHighScore.txt")));
String inputString;StringBuffer stringBuffer = new StringBuffer();
while ((inputString = inputReader.readLine()) != null && i < 6)
{
if((inputString = inputReader.readLine()) != space)
{
stringBuffer.append(inputString + "\n");
i++;
score[i] = stringBuffer.toString();
}
}
currentScoreSaved = stringBuffer.toString();
FileOutputStream fos = openFileOutput("localHighScore.txt", Context.MODE_PRIVATE);
while (i < 6)
{
i++;
fos.write(score[i].getBytes());
fos.write(space.getBytes());
}
fos.write(localHighScore.getBytes());
//fos.newLine(); //I thought this was how you did a new line but sadly I was mistaken
fos.close();
}
catch(Exception e)
{
e.printStackTrace();
}
Now you will notice this doesn't re arrange the score if a new highscore is achieved. That I am planning on doing next. For the moment I am just trying to get the program to do the main thing which is read in the current data, stick it in an Array then print it back to that file along with the new score
Any Ideas how this might work, as currently it's printing out nothing even when I had score in the textfile before hand
I'm only a first year student in Java programming and I am a new user here at stackoverflow.com, so pardon me if coding for android has some special rules I don't know about, which prevents this simple and humble example from working. But here is how I would read from a file in the simplest of ways.
File tempFile = new File("<SubdirectoryIfAny/name_of_file.txt");
Scanner readFile = new Scanner( tempFile );
// Assuming that you can structure the file as you please with fx each bit of info
// on a new line.
int counter = 0;
while ( readFile.hasNextLine() ) {
score[counter] = readFile.nextLine();
counter++;
}
As for the writing back to the file? Put it in an entirely different method and simply make a simplified toString-like method, that prints out all the values the exact way you want them in the file, then create a "loadToFile" like method and use the to string method to print back into the file with a printstream, something like below.
File tempFile = new File("<SubdirectoryIfAny/name_of_file.txt");
PrintStream write = new PrintStream(tempFile);
// specify code for your particular program so that the toString method gets the
// info from the string array or something like that.
write.print( <objectName/this>.toStringLikeMethod() );
// remember the /n /n in the toStringLikeMethod so it prints properly in the file.
Again if this is something you already know, which is just not possible in this context please ignore me, but if not I hope it was useful. As for the exceptions, you can figure that you yourself. ;)
Since you are a beginner, and I assume you are trying to get things off the ground as quickly as possible, I'd recommend using SharedPreferences. Basically it is just a huge persistent map for you to use! Having said that... you should really learn about all the ways of storage in Android, so check out this document:
http://developer.android.com/guide/topics/data/data-storage.html
The Android docs are awesome! FYI SharedPreferences may not be the best and awesomest way to do this... but I'm all for quick prototyping as a learner. If you want, write a wrapper class around SharedPreferences.

Categories