H guys,
I'm having a piece of code which would search for some similar .ser files and loads them into a list
the files are (rulesIncr1.ser,rulesIncr2.ser, rulesIncr3.ser ...... and so on)
now to load all the files i have written the following logic
String defaultfilename = "rulesincr";
int i=1;
String incrFile;
//THE FOLLOWING CODE WILL CHECK FOR ANY NU8MBER OF INCR RULES FILE IN THE LOCATION AND ADD THEM TO A RULE MODEL LIST
do
{
String tempincr = new Integer(i).toString();
incrFile = defaultfilename.concat(tempincr).concat(".ser");
FileInputStream fis= new FileInputStream( filePath.concat(incrFile));
ObjectInputStream inStreamIncr = new ObjectInputStream(fis);
myRulesIncr = (List<RuleModel>)inStreamIncr.readObject();
i++;
}
while(new File(filePath.concat(incrFile)).isFile());
Now the problem I'm facing is each and every time myRulesIncr would be refreshed and only the last file is loaded at the end. I need to have all the loaded files. Please advise
Thanks
The line
myRulesIncr = (List<RuleModel>)inStreamIncr.readObject();
in your loop will always override the List to which the myRulesIncr variable points. If you want to add all those RuleModel instances to myRulesIncr you should have something like
List<RuleModel> myRulesIncr = new ArrayList<RuleModel>();
while{
//your while loop without the
//myRulesIncr = (List<RuleModel>)inStreamIncr.readObject(); line
myRules.addAll( (List<RuleModel>)inStreamIncr.readObject() );
}
Im unfamiliar with the standard list object but the problem appears to be here:
myRulesIncr = (List<RuleModel>)inStreamIncr.readObject();
You appear to be making a new list every time, and even if not I believe you need to increment to the next node ie myRulesIncr = myRulesIncr.next()
Related
I'm currently developing a POS till system as a university assignment and I'm completely stumped on a for loop that I need to implement to save any data that gets added to the system by the end user. The save() function is meant to save any data put into the program to 1 of 2 .txt files (stock or till).
I've currently built the save function for each of the different instance variables but when it runs through the save() method it'll only run once (obviously) and I'm having a hard time understanding how to implement a sample for loop as a solution.
Here's my current progress:
public void save() throws IOException {
// IMPLEMENTATION
PrintWriter outfileStock = new PrintWriter(new FileWriter(SHOP_STOCK_DATA_FILE));
outfileStock.println(barcode);
outfileStock.println(cost);
outfileStock.println(quantity);
outfileStock.close();
PrintWriter outfileTill = new PrintWriter(new FileWriter(SHOP_TILL_DATA_FILE));
outfileTill.println();
outfileTill.println();
outfileTill.println();
outfileTill.close();
}
The sample for loop we've been given (from a worksheet that lead up to this assignment is this:
public void save(String fileName) throws IOException {
PrintWriter outfile = new PrintWriter(new FileWriter(fileName));
outfile.println(type);
outfile.println(face);
outfile.println(hair);
outfile.println(powerPoints);
outfile.println(loot.size());
for (Treasure treasure : loot) {
outfile.println(treasure.getName());
outfile.println(treasure.getValue());
}
outfile.close();
While I'm not asking for the code to be written for me, it would be great if somebody to explain how the
for (Treasure treasure : loot) {
outfile.println(treasure.getName());
outfile.println(treasure.getValue());
}
loop works. I can provide some more info if needed, fairly new to Java so not sure how much is needed to understand.
loot is an ArrayList that contains Treasure objects.
for (Treasure treasure : loot) {
outfile.println(treasure.getName());
outfile.println(treasure.getValue());
}
loops over each one of the Treasure objects (each one of which are temporarily assigned to treasure) by this line of code:
for (Treasure treasure : loot) {
which means (for every Treasure object in loot which you call treasure)
and gets (for each) their name (treasure.getName()) and their values (treasure.getValue()).
:
stands for the enhanced for-loop which was introduced in Java SE 5.0. See more info here:
https://blogs.oracle.com/CoreJavaTechTips/entry/using_enhanced_for_loops_with
Basically, instead of
for (int i=0; i < array.length; i++) {
System.out.println("Element: " + array[i]);
}
you can now do
for (String element : array) {
System.out.println("Element: " + element);
}
loot seems to be a List of some sort. What the for loop will do is take each element of this list and return them to you as a single object called treasure. when you get this element back you can treat is as a normal Treasure object. In your case it seems to be writing the treasure name and value to a file.
For each loop
This is basic Java. The variable loot is something that can be iterated over. It's either an array or one of the container classes like ArrayList. It contains Treasure objects.
For each element in the loot array, those two lines of code are executed.
loot is a List. Therefore using this enhanced for loop it fetch the each element in each iteration and assign it to the treasure variable. But here you don't have access to the previous element of the list in a given time. If you use other for loop for(int x=0; x < size ; x++ ) in each iteration you can access previous or next element by coding `loot.get(x-1) or loot.get(x+1). Therefore it depends on your requirement.
I seem to be having an issue with not properly syntaxing my code, but as I've just started out with learning I seem to be missing the error. It's a homework assignment, where I need to use an Array of JxploreFile-objects. This is the part of the code I'm having trouble with:
private JxploreFile[] getSubFolders()
{
File subFiles[];
subFiles = file.listFiles();
File subFolders[];
int p = 0;
for(int i = 0; i < subFiles.length; i++)
{
if(subFiles[i].isDirectory() == true)
{
Array.set(subFolders, p, subFiles[i]);
}
}
JxploreFile foldersToReturn[] = new JxploreFile[subFolders.length];
for(int i=0; i < subFolders.length; i++)
{
foldersToReturn[i] = new JxploreFile(subFolders[i]);
}
return foldersToReturn;
}
Specifically, the for-loop where I'm trying to add the files marked as .isDirectory into a new Array. I've also tried other methods by placing each new file coming from the subFiles Array manually into the subFolders Array by declaring indexnumbers, but this also turned out faulty. At this point I'm out of ideas and I hope there is someone who can point me out the obvious, as I'm probably missing something reallly basic.
Edit:
I'm sorry for the incomplete post, It's the first time I actually post here as I usually try to filter my own problems out of the posts of others. The error I got was indeed that 'subFolders' had not been initialized yet, which I didn't understood because on the sixth line I wrote
File subFolders[];
which as far as I know should declare the variable subFolders to become an Array, or is this where I went wrong?
Also, my question might not have been specific enough, I'm looking for what causes the error (which I didn't mention at all): why 'subFiles' wasn't initialized.
The array subFolders has not been initialized properly. In order to use the array in the Array.set method it must be initialized and allocated with a size.
An alternative approach for this is to use a List instead. Lists are good when you are working with data that is more dynamic e.g. when you do not know the size of the array. Then you can simplify your code like this:
File[] subFiles = file.listFiles();
// Create the list
List<JxploreFile> subFolders = new ArrayList<>();
// Add all the sub folders (note that "file" is a bit magic since it
// is not specified anywhere in the original post
for (File subFile : file.listFiles()) {
if (subFile.isDirectory()) {
subFolders.add(new JxploreFile(subFile));
}
}
// Return an array
return subFolders.toArray(new JxploreFile[subFolders.size()]);
You can also simplify the whole thing even further by using a Java 8 stream like this:
return Arrays.stream(file.listFiles())
.filter(File::isDirectory)
.toArray(JxploreFile[]::new);
For more info:
Creating Objects in Java
Arrays
There is no question in your post, but anyway here the problems I found in your code :
File subFolders[];
int p = 0;
for(int i = 0; i < subFiles.length; i++)
{
if(subFiles[i].isDirectory() == true)
{
Array.set(subFolders, p, subFiles[i]);
}
}
when calling Array.set you never initialized subFolders which will throw a NullPointerException.
Also, you dont need to do
if(subFiles[i].isDirectory() == true)
you can simply do
if(subFiles[i].isDirectory())
as subFiles[i].isDirectory() is already a condition.
So this is my first time posting here. I am trying to read data from a file, create multiple objects from that data, and then place the created objects into an ArrayList. But every time I have tried, I just get multiple copies of the same object, instead of different objects. I am at my wits end.
Anyways, here is the code for the method to read the data in from the file. Thanks in advance for any help!
public void openShop() throws IOException{
System.out.println("What is the name of the shop?");
shopName = keyboard.nextLine();
setShopFile();
File openShop = new File(shopFile);
if (openShop.isFile()){
Scanner shopData = new Scanner(openShop);
shopName = shopData.nextLine();
shopOwner = shopData.nextLine();
while (shopData.hasNextLine()){
shopItem.setName(shopData.nextLine());
shopItem.setPrice(Double.parseDouble(shopData.nextLine()));
shopItem.setVintage(Boolean.parseBoolean(shopData.nextLine()));
shopItem.setNumberAvailable(Integer.parseInt(shopData.nextLine()));
shopItem.setSellerName(shopData.nextLine());
shopInventory.add(shopItem);
}
setNumberOfItems();
}
else
System.out.println("That shop does not exist. Please try to open" +
"the shop again.");
isSaved = true;
}
inside your while loop you should create a new instance of an object. Else it would only end up making modifications to the exisiting instance.
Correct way :
while (shopData.hasNextLine()){
shopItem = new ShopItem(); //This will create a new Object of type ShopItem
shopItem.setName(shopData.nextLine());
shopItem.setPrice(Double.parseDouble(shopData.nextLine()));
shopItem.setVintage(Boolean.parseBoolean(shopData.nextLine()));
shopItem.setNumberAvailable(Integer.parseInt(shopData.nextLine()));
shopItem.setSellerName(shopData.nextLine());
shopInventory.add(shopItem);
}
I cant see where you're creating the shopItem instance.
But if you're not creating a new ShopItem each time then every time you go around the loop you're just updating the one instance, and then adding it to the shopInventory.
You fill your ArrayList using the very same object. You should create a new instance of ShopItem:
while (shopData.hasNextLine()){
ShopItem shopItem = new ShopItem();
shopItem.setName(shopData.nextLine());
...
}
I've got a text file that has 173,139 words delimited by newlines. Basically, I need to load this 1.7mb file into an array of strings, for easy access. I'm trying to do this in onCreate() for the main activity, which might cause problems of its own because it might make starting the application really slow, but right now I'm just trying to load in the dictionary, I suppose.
I looked up the problem and found that I should use asset manager for this problem, so here's what I have in my Dictionary class:
public class Dictionary {
private String[] dictionary = new String[173139];
private String[] acceptedWordsList = new String[173139];
private String acceptedWords = "";
public Dictionary(Context context){
AssetManager am = context.getAssets();
try {
String rawText;
int element = 0;
InputStream is = am.open("words.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
while((rawText=reader.readLine()) != null){
dictionary[element++] = rawText;
}
} catch (IOException e) {
e.printStackTrace();
}
}
and I'm instantiating a Dictionary in my Main Activity in pretty much the first line in the class:
public class MainActivity extends Activity {
Dictionary dictionary = new Dictionary(this);
//rest of application code
}
What am I doing wrong here? I've also tried instantiating a Dictionary like this:
Dictionary dictionary = new Dictionary(this.getApplicationContext());
as well as:
Dictionary dictionary = new Dictionary(getApplicationContext());
but all of these seem to cause fatal errors in my application.
So two final questions: is it okay to instantiate in the beginning of the application code like that? And if so, why doesn't that code work when I'm trying to do so?
edit: I was asked for logcat output. My apologies, this is my first "real" android program. I don't know if this is exactly what you're looking for, but I don't want to omit anything that might be helpful either:
http://pastebin.com/raw.php?i=c99LFZzx
Just a thought: your context.getAssets call throws the NPE (possibly because context is null).
I think that's because you did not put Dictionary dictionary = new Dictionary(this); in the onCreate method actually.
I would expect it to work (provided the file is there) if you put that code on onCreate, after super.onCreate(bundle).
If you are worried about app initialization loading time, I suggest you use an AsyncTask to load your dictionary in a splash activity, so you can provide user feedback.
OK this method reads a dirctor, verify the file paths are ok and then pass each file to a method and updates a Map object.
But how can i explain this for java doc. I want to create a java doc and how should i explain this method for the documentation purpose. Please tell me, if you can help me with this example, i can work for my whole project. thank you:
private void chckDir() {
File[] files = Dir.listFiles();
if (files == null) {
System.out.println("Error");
break;
}
for (int i = 0; i < files.length; i++) {
File file = new File(files[i].getAbsoluteFile().toString());
Map = getMap(file);
}
}
Your method doesn't do what you said In your first sentence (doesn't verify file paths, and throws the result of getMap() away), but there's nothing wrong with putting that kind of sentence im the Javadoc.
There are some issues with your code:
The break statement will give a compilation error, I think. It should be a return.
It is bad style to name a field with a capital letter as the first character. If Dir and Map are field names, they should be dir and map respectively.
The statement Map = getMap(file); is going to repeatedly replace the Map field, and when you exit the loop, the field will refer to the object returned by the last getmap call. This is probably wrong.
Finally, change the file declaration as follows. (There is no need to create a new File object ... because getAbsoluteFile() reurns a File)
File file = files[i].getAbsoluteFile();