Reading / Sorting And Writing A File
Dec 4, 2014
I need to read lastname, firstname, and ssn from a text file and sort them based on oneof those three creiteria. Here is my person class:
public class Person implements Comparable {
private String lastName, firstName, ssn;
private static int sortBy = 1;
public static final int LASTNAME=1, FIRSTNAME=2, SSN=3;
public void setSortMethod(int method) {
if(method != LASTNAME && method != FIRSTNAME && method != SSN) {
throw new IllegalArgumentException();
} else {
[code]....
how to sort my info and store it into an array and then write that info into my new file.
View Replies
ADVERTISEMENT
Sep 9, 2014
I've looked at multiple sources and everyone is saying different stuff. Which one should I be using? FileWriter/FileReader, other people was saying PrintWriter, and one even said : "Formatter" which is the one I'm doubting mostly. My purposes for writing files is for like saving maps, saving high scores, etc.
View Replies
View Related
Jan 10, 2014
I have accountsData.txt file in my default package, this is the file it should be writing to and reading from.
There is an ATM class, which has the main in it. From here the program is supposed to work like an atm, you type in your account number and can withdraw or deposit. It is supposed to then write the changes to the file.
//Read from a file.
public void loadAccounts(String inputFileName) throws IOException
{
Scanner fin = new Scanner(new File(inputFileName));
// Variables to store the values.[/color]
int account = 0;
double balance = 0.0;
[Code] .....
View Replies
View Related
Jan 19, 2014
I have a program that writes a user's input to a file.
The input consists of several loops. In each loop the user enters a student number, the student first name and last name and then several exam results. Each student has different number of exams, depend on the user input.
For instance, the input can be (explanations are in brackets but not in the actual file):
505 (student number)
efron (last name)
ben (first name)
3 (no. of exams)
88 (1st exam mark)
70 (2nd exam mark)
... and so on
I need to write a program that reads that file and writes it to the screen, but it needs to do it in ascending order according to the student number.
Leaving aside the format it will be displayed on the screen, my question is how should I sort the data by the student number?
I though about first reading each student as an array, but my problem is that each array contains different number of elements (depends on the number of exams) and also each array containד both strings (first and last names) and ints.
View Replies
View Related
Oct 11, 2014
I'm having a bit of trouble with using the Scanner and the Printwriter. I start with a file like this (1 = amount of Houses in the file)
1
FOR SALE:
Emmalaan 23
3051JC Rotterdam
7 rooms
buyprice 300000
energylevel C
The user gets (let's say for simplicity) 3 options:
1. Add a House to the file,
2. Get all Houses which fullfil requirements (price, FOR SALE / SOLD etc.) and
3. Close the application.
This is how I start:
Scanner sc = new Scanner (System.in);
while (!endLoop) {
System.out.println("Make a choice);
System.out.println("1) Add House");
System.out.println("2) Show Houses");
System.out.println("3) Exit");
int choice = sc.nextInt();
Then I have a switch for all of the three cases. I keep the scanner open, so Java can get the user input (house = for sale or sold, price = ... etc). If the user chose option 1, and all information needed is inputted and scanned, the House will be written to the file (which looks like what I typed above).
For this, I use try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("Makelaar.txt", false)))). This works perfectly (at least so it seems.)
If the user chose option 1, and all requirements are inputted and scanned, the Houses will be read (scanner) from the file and outputted. For this I use the same Scanner sc. This also works perfectly (so it seems atleast).
My problem is as follows: If a House has been added, I can only read the House(s) which were already in the file. Let's say I have added 2 houses, and there were from the start 3 houses. If option 2 is chosen, the first 3 houses will be scanned perfectly. An exception will be caught for the remaining 2 (just added) Houses. How can I solve this? I tried to close the Scanner, and reopening it, but apparently Java doesn't agree with this
View Replies
View Related
May 17, 2014
I have copied a wav file as explained in [URL] ..... When trying to play my new file, it runs but no sound is hear. My reading and writing class is as explained in another post in the site:
This is the function that reads the file:
// read a wav file into this class
public boolean read(DataInputStream inFile) {
myData = null;
byte[] tmpInt = new byte[4];
byte[] tmpShort = new byte[2];
[Code] ....
I can't hear the copied wav file, but still the wav file is correctly copied...
View Replies
View Related
Nov 11, 2014
public class Tester
{
public static void main(String[] args)
{
Product p1 = new Product();
p1.loadFromFile("Monitor.pr");
System.out.println("Actual: " + p1.toString());
System.out.println("Expected: Product [id=12345, name=Monitor, description=A freakin great monitor!]");
p1.setId(11111);
p1.setName("another product");
p1.setDescription("Description of another product!");
[code]....
The expected output is what my program should be doing and the actual output is what it's doing instead. As you can see, my code works for the middle test. But I cannot understand why it won't load the first fileFor the second half, the id and the quantity are separated by a comma... I'm not really sure how to deal with that. As you can see, I tried using a delimiter, but it doesn't seem to be doing any good.
View Replies
View Related
Apr 17, 2015
have to create a file named Lab13.txt. In the file I have 10 random numbers. I have to import the 10 numbers and have to Multiply all the numbers from Lab13.txt by 10 and save all the new numbers a new file named Lab13_scale.txt. so if the number 10 is in lab13.txt it prints 100 to Lab13_scale.txt. how do i get it to Multiply Here is what I have:
Java Code: import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
[Code].....
View Replies
View Related
Nov 20, 2014
I have a project where I am required to read and write a vector of bank account objects and I am struggling with this concept. I was able to figure it out when the accounts were not stored in a vector but now that I am dealing with vectorsThis is my best attempt. Even though I know it's wrong, what I am trying to do.write/read methods in main:
public static void readTrans()
{
textArea.setText("");
chooseFile(1);
try
{
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(fis);
for (int index=0; index != fileIndex; index++)
[code]....
View Replies
View Related
Jul 10, 2014
I am using a FileOutputStream to write a file but it is not writing data to destination file from source
Here is my code
package org.kishor.outputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteToaFile {
public static void main(String args[]) throws IOException
{
FileOutputStream fout = null;
[code]...
find a bug where i am wrong why data is not on output file?
View Replies
View Related
Dec 9, 2014
I am working on a project that requires me to build a database with random access file, representing products, the base product contains a name (about 30 characters), a price (double), and a quantity (integer). I have worked on this project for probably 15+ hours and have tried so many things and feel like I've barley made any progress...
The part i am really struggling with is taking the data from the text file and creating an object array with it using the product class. Once ive accomplished that, i have to use that data to create a random access file with the data. Here is the base Product class that must be used to create the objects for the array.
public class Product
{
public String pName;
public String stringName;
public double price;
public int quanity;
[Code]...
these continue for about 40-50 entries, they are not seperated by a blank line though i had to add those so it would display correctly, each entry is on its own line with name seperated with spaces, then price after a comma, then quanity after the second comma.....
View Replies
View Related
Dec 8, 2014
I am working on a project that requires me to build a database with random access file, representing products, the base product contains a name (about 30 characters), a price (double), and a quantity (integer). I have worked on this project for probably 15+ hours and have tried so many things and feel like I've barley made any progress...
The part i am really struggling with is taking the data from the text file and creating an object array with it using the product class. Once ive accomplished that, i have to use that data to create a random access file with the data.
Here is the base Product class that must be used to create the objects for the array.
public class Product
{
public String pName;
public String stringName;
public double price;
public int quanity;
//Constructor
public Product( String pName, double price, int quanity )
[code]....
and then here is the data from the text file that i must extract to use to create product objects.
Dill Seed,938,34
Mustard Seed,100,64
Coriander Powder,924,18
Turmeric,836,80
Cinnamon (Ground Korintje),951,10
Cinnamon (Ground) Xtra Hi Oil (2x),614,31
Cinnamon (Ground) High Oil (1X),682,19
these continue for about 40-50 entries, they are not separated by a blank line though i had to add those so it would display correctly, each entry is on its own line with name separated with spaces, then price after a comma, then quanity after the second comma.....
View Replies
View Related
Oct 13, 2014
So we have to create a code that reads in a file that has a huge list of words. Our code has to convert every word to all lower cases and then re-sort alphabetically. I was able to turn everything to lower case, but for the re-sorting I keep getting a null pointer exception on the line of the if statement.
import java.io.*;
public class readDict {
public static void main(String args[]) {
try {
System.out.println("Opening the file...");
[Code] ....
View Replies
View Related
Apr 11, 2013
I have a problem sorting this file alphabetically by second name. Basically, my method sorts each column alphabetically but i would like to sort the file according to the second name.
File:
Moe Carl
Saul Sergio
Rocky Louis
Ike Ziken
This is how my method sorts the file:
Ike Carl
Moe Louis
Rocky Sergio
Saul ziken
Instead
Moe Carl
Rocky Louis
Saul Sergio
Ike Ziken
Code :
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
class thedata implements Comparable
{
private String firstname;
private String secondname;
[Code] .....
View Replies
View Related
Dec 15, 2014
I need to write a program that, when a button is pressed, will add the user input to a table AND write it to a sequential data file. I have everything done accept for how to write the data sequentially(all input data on the same line in the file). The following is part of the code:
private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel dtm = (DefaultTableModel)jTable1.getModel();
dtm.addRow(new Object[]{donorName.getText(),charityName.getText(),donationAmmount.getText()});
//Adds user input to the table
try
{
FileWriter writer = new FileWriter("FundraisingInformation.txt",true);//Creates file or adds to it
BufferedWriter bw = new BufferedWriter(writer);
[code].....
I would need the file output to be in the following format:
donorName charityName donationAmmount
As I said, using the .write(bw) i know how to make it look like:
donorName
charityName
donationAmmount
View Replies
View Related
Nov 29, 2014
I want a servlet to write a file inside WEB-INF folder
I tried these things
File file =new File("feedback.txt");
or
File file =new File("/feedback.txt");
or
File file =new File("WEB-INF/feedback.txt");
View Replies
View Related
Apr 20, 2014
I am trying to write a Float Array to a file but it is only writing the last line of the array to a file. I have also attached the entire assignment as a zip file with all required files. Here is the part of the code I am having issues with:
Java Code:
for (int i = 0; i < differenceArray.length; i++){
System.out.println ("Date: "+ dateArray[i] + " Opening: " + dataArray[i][2] + " Closing: "+ dataArray[i][5] + " Difference: " + differenceArray[i]);
try(FileWriter writer = new FileWriter("C: emp" + fileName + ".txt")){
writer.write(Float.toString(differenceArray[i]));
[Code] .....
View Replies
View Related
Jul 19, 2014
There are several ways in Java to create a text file and write to it. But which is the most effective way among them? Any example with code?
View Replies
View Related
Oct 25, 2014
I am creating a car simulator that simulators the odometer and fuel gauge on a car. I want to print the results to a text file but it seems to be printing only the last two lines instead of all of them. How can I make it so it doesn't overwrite the previous input?
Here's my main method:
public static void main(String[] args) throws FileNotFoundException {
CarInstrumentSimulator carInstrumentSimulator = new CarInstrumentSimulator();
FuelGauge gas = carInstrumentSimulator.new FuelGauge();
[Code].....
View Replies
View Related
Jan 13, 2014
I was writing a method to read a file. I did not think it through and gave the return type as void and modifier as static but I am not sure if it has to be void. How do you decide the return type of the method? Is there a good rule of thumb in such cases? Also, does the use of static needs to be done sparingly?
View Replies
View Related
May 12, 2014
I have requirement of sorting the files in tree structure with name and timestamp of creation, i am new to swings...
Here we are using FileTreeModel.
Root Folder:
folder1;
file1
file2
.
.
View Replies
View Related
Oct 16, 2014
how to sort my text file. So far I have been able to read the text file and print it back out, but I am unsure of how to go about sorting it. Must print the colors (in the order of the rainbow first) and if the colors are the same compare the size (bigger is more important)The values I have to sort are written as such in the text file:
blue 18
blue 10
red 27
yellow 4
public class Rainbow{
private String color;
private int size;
public Rainbow(String color, int size){
this.color = color;
this.size = size;
[code]....
I would know how to sort it if it was supposed to be alphabetical order or there were only numbers, but I can't seem to figure out how to sort it when there are strings and integers
View Replies
View Related
Jan 11, 2015
How to output text to a file, so I had to do my own research on google, but the results I found were confusing. I finally got my code to write to a file, but I cannot figure out how to append a new line. I know what part of the code is incorrect, but I don't know how to fix it. here is what I have right now:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
public class highscore {
public static void main(String[] args) throws IOException {
[Code] ....
I can see the last two lines are telling the program to overwrite the first input with the second. Of course if I pick a different file name for the second output, I get another file with the second input, but I need to learn how to append as well.
View Replies
View Related
May 25, 2014
My program creates a file but cannot write to it and i cannot figure out why.
How can i fix this code so that the FileOutputStream writes the String "Output" to the file HighScore.
public boolean ScoreWriter(int HighScore, int ScoreNum){
boolean writ = true;
System.out.println(HighScore + " " + ScoreNum);
try{
File ScoreFile = new File("HighScore");
if (!ScoreFile.exists()){
ScoreFile.createNewFile();
}else if (ScoreFile.exists()){
ScoreFile.delete();
ScoreFile.createNewFile();
[code].....
View Replies
View Related
Feb 8, 2014
I'm writing a program to dynamically update an xml file to add, delete, and edit entries in the file. I've run into an issue with the add method because when I write into the file, a random letter is added before the line. EX:
I want to add "<item> ..." to the end of the list of entries, but when it is added, this is what is added "Z <item> ..."The spacing for the <item> is correct, however, I don't see where or why the Z is added.
public static void insertItem(Item i)
{
try {
String insert = " <item>";
String text = "";
Scanner in = new Scanner(file);
[code]....
View Replies
View Related
Aug 20, 2014
I obtained the following code online which purports to get the content of the JFrame:
public BufferedImage getScreenShot(
Component component) {
BufferedImage image = new BufferedImage(
winWidth,
[Code] .....
Then I write out the image with the following code:
BufferedImage screenShot = getScreenShot(c);
try{
File outputfile = new File(
[Code] .....
When I double-click on the resulting file, all the images show up as black rectangles in Windows Photo Viewer. Yet the associated buffered image displays correctly in the window. I've tried 'jpg, 'png', and 'bmp' extensions, with matching formats in the write. I am using Win-7 64-bit. and jdk8 with matching jre.
View Replies
View Related