Reading from file into an array
Hello, new to Java and we need to modify a mortgage calculator to read interest rate from a file into an array and not have them hard coded in the program. I have read many post on how to perform this but am lost on where to put the new code and format. Here is my code and I hope I posted this right.
import javax.swing.*; // Imports the Main Swing Package
import javax.swing.event.*;
import javax.swing.text.*; // Used for Text Box Caret Position
import java.awt.*; // Imports the main AWT Package
import java.awt.event.*; // Event handling class are defined here
import java.text.NumberFormat;
import java.text.*; // Imports the Main Text Package
import java.util.*; // Imports the Main Utility Package
public class mortgageCalculator1 extends JFrame implements ActionListener // Creates class mortgageCalculator
JLabel AmountLabel = new JLabel(" Enter Mortgage Amount:$ "); // Declares Mortgage Amount Label
JTextField mortgageAmount = new JTextField(10); // Declares Mortgage Amount Text Field
JButton IntandTerm1B = new JButton("7 years at 5.35%"); // Declares 1st Mortgage Term and Interest Rate
JButton IntandTerm2B = new JButton("15 years at 5.50%"); // Declares 2nd Mortgage Term and Interest Rate
JButton IntandTerm3B = new JButton("30 years at 5.75%"); // Declares 3rd Mortgage Term and Interest Rate
JLabel PaymentLabel = new JLabel(" Monthly Payment: "); // Declares Monthly Payment Label
JTextField monthlyPayment = new JTextField(10); // Declares Monthly Payment Text Field
JButton exitButton = new JButton("Exit"); // Declares Exit Button
JButton newcalcButton = new JButton("New Calculation"); // Declares New Calculation Button
JTextArea mortgageTable = new JTextArea(35,65); // Declares Mortgage Table Area
JScrollPane scroll = new JScrollPane(mortgageTable); // Declares ScrollPane and puts the Mortgage Table inside
public mortgageCalculator1() // Creates Method
super("MORTGAGE CALCULATOR"); // Title of Frame
JMenuBar mb = new JMenuBar(); // Cretes Menu Bar
JMenu fileMenu = new JMenu("File"); // Creates File Menu
fileMenu.setMnemonic('F'); // Enables alt + f to Access File Menu
JMenuItem exitItem = new JMenuItem("Exit"); // Creates Exit in File Menu
fileMenu.add(exitItem); // Adds Exit to File Menu
exitItem.addActionListener(new ActionListener() // Adds Action Listener to the Exit Item
public void actionPerformed(ActionEvent e) // Tests to Verify if File->Exit is Pressed
System.exit(0); // Exits the Programs when File->Exit is Pressed
mb.add(fileMenu); // Adds the File Menu
setJMenuBar(mb);
setSize(600, 400); // Sets Size of Frame
setLocation(200,200); // Sets the Location of the Window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Command on how to close frame
JPanel pane = new JPanel(); // Declares the JPanel
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS)); // Sets Panel Layout to BoxLayout
Container grid = getContentPane(); // Declares a Container called grid
grid.setLayout(new GridLayout(4,3,5,5)); // Sets grid Layout to GridLayout
pane.add(grid); // Adds the grid to the Panel
pane.add(scroll); // Addes the scrollPane to the Panel
grid.setBackground(Color.yellow); // Set grid color to Yellow
setCursor(new Cursor(Cursor.HAND_CURSOR)); // Makes the cursor look like a hand
mortgageAmount.setBackground(Color.black); // Sets mortgageAmount JPanel JTextField Background Color
mortgageAmount.setForeground(Color.white); // Sets mortgageAmount JPanel JTextField Foreground Color
mortgageAmount.setCaretColor(Color.white); // Sets mortgageAmount JPanel JTextField Caret Color
mortgageAmount.setFont(new Font("Lucida Sans Typewriter", Font.PLAIN, 18)); // Sets mortgageAmount JPanel JTextField Font
monthlyPayment.setBackground(Color.black); // Sets monthlyPayment JPanel JTextField Background Color
monthlyPayment.setForeground(Color.white); // Sets monthlyPayment JPanel JTextField Foreground Color
monthlyPayment.setFont(new Font("Lucida Sans Typewriter", Font.PLAIN, 18)); // Sets monthlyPayment JPanel JTextField Font
mortgageTable.setBackground(Color.yellow); // Sets mortgageTable JTextArea Background Color
mortgageTable.setForeground(Color.black); // Sets mortgageTable JTextArea Foreground Color
mortgageTable.setFont(new Font("Arial", Font.PLAIN, 18)); // Sets JTextArea Font
grid.add(AmountLabel); // Adds the Mortgage Amount Label
grid.add(mortgageAmount); // Adds the Mortgage Amount Text Field
grid.add(IntandTerm1B); // Adds 1st Loan and Rate Button
grid.add(PaymentLabel); // Adds the Payment Label
grid.add(monthlyPayment); // Adds the Monthly Payment Text Field
monthlyPayment.setEditable(false); // Disables editing in this Text Field
grid.add(IntandTerm2B); // Adds 2nd Loan and Rate Button
grid.add(exitButton);
grid.add(newcalcButton); // Adds the New Calc Button
grid.add(IntandTerm3B); // Adds the Exit Button
setContentPane(pane); // Enables the Content Pane
setVisible(true); // Sets JPanel to be Visable
exitButton.addActionListener(this); // Adds Action Listener to the Exit Button
newcalcButton.addActionListener(this); // Adds Action Listener to the New Calc Button
IntandTerm1B.addActionListener(this); // Adds Action Listener to the 1st loan Button
IntandTerm2B.addActionListener(this); // Adds Action Listener to the 2nd loan Button
IntandTerm3B.addActionListener(this); // Adds Action Listener to the 3rd loan Button
mortgageAmount.addActionListener(this); // Adds Action Listener to the Mortgage Amount Text Field
monthlyPayment.addActionListener(this); // Adds Action Listener to the Monthly payment Text Field
public void actionPerformed(ActionEvent e) // Tests to Verify Which Button is Pressed
Object command = e.getSource(); // Enables command to get data
if (command == exitButton) //sets exitButton // Activates the Exit Button
System.exit(0); // Exits from exit button // Exits from exit button
int loanTerm = 0; // Declares loanTerm
if (command == IntandTerm1B) // Activates the 1st Loan Button
loanTerm = 0; // Sets 1st value of Array
if (command == IntandTerm2B) // Activates the 2nd Loan Button
loanTerm = 1; // Sets 2nd value of Array
if (command == IntandTerm3B) // Activates the 3rd Loan Button
loanTerm = 2; // Sets 3rd value of Array
double mortgage = 0; // Declares and Initializes mortgage
double rate = 0; // Declares and Initializes rate
double [][] loans = {{7, 5.35}, {15, 5.50}, {30, 5.75},}; // Array Data for Calculation
try
mortgage = Double.parseDouble(mortgageAmount.getText()); // Gets user input from mortgageAmount Text Field
catch (NumberFormatException nfe) // Checks for correct number fformatting of user input
JOptionPane.showMessageDialog (this, "Error! Invalid input!"); // Outputs error if number is wrong format or nothing is entered
return;
double interestRate = loans [loanTerm][1]; // Sets interestRate amount
double intRate = (interestRate / 100) / 12; // Calculates Interst Rate
double loanTermMonths = loans [loanTerm] [0]; // Calculates Loan Term in Months
int months = (int)loanTermMonths * 12; // Converts Loan Term to Months
double interestRateMonthly = (intRate / 12); // monthly interst rate
double payment = mortgage * intRate / (1 - (Math.pow(1/(1 + intRate), months))); // Calculation for Monthly payment
double remainingLoanBalance = mortgage; // Sets Reamaining Balance
double monthlyPaymentInterest = 0; // holds current interest payment
double monthlyPaymentPrincipal = 0; // holds current principal payment
NumberFormat myCurrencyFormatter = NumberFormat.getCurrencyInstance(Locale.US); // Number formatter to format output in table
monthlyPayment.setText(myCurrencyFormatter.format(payment));
mortgageTable.setText("Month\tPrincipal\tInterest\tEnding Balance\n" + // Formats morgageTable Header
"---------\t----------\t------------\t---------------------\n");
for (;months > 0 ; months -- )
monthlyPaymentInterest = (remainingLoanBalance * intRate); // Calculation for Monthly Payment Toward Interest
//Calculate H = R x I
monthlyPaymentPrincipal = (payment - monthlyPaymentInterest); // Calculation for Monthly Payment Toward Principal
//Calculate C = P - H
remainingLoanBalance = (remainingLoanBalance - monthlyPaymentPrincipal); // Calculation for Reamining loan Balance
// Calculate R = R - C
// H = monthlyPaymentInterest
// R = remainingLoanBalance
// P = payment
// C = monthlyPaymentPrincipal
// I = interestRateMonthly
mortgageTable.setCaret (new DefaultCaret()); // Sets Scroll position to the top left corner
mortgageTable.append(String.valueOf(months) + "\t" + // Pulls in data and formats MortgageTable
myCurrencyFormatter.format(monthlyPaymentPrincipal) + "\t" +
myCurrencyFormatter.format(monthlyPaymentInterest) + "\t" +
myCurrencyFormatter.format(remainingLoanBalance) + "\n");
if(command == newcalcButton) // Activates the new calculation Button
mortgageAmount.setText(null); //clears mortgage amount fields
monthlyPayment.setText(null); //clears monthly payment fields
mortgageTable.setText(null); //clears mortgage table
public static void main(String[] args) //This is the signature of the entry point of all the desktop apps
new mortgageCalculator1();
}
OK, making a little progress but am still very confused.
What I have is a file (int&term.dat) with three lines;
5.75, 30
5.5, 15
5.35 ,7
I have three JButtom that I what to read a seperate line and place the term in a term TextField and a rate in a Rate TextField
I have added the following code and all it does now is output a black space to the screen; I am working with one Button and Just the rate for now to try and get it to work. I have been looking at the forums, reading the internet and several books to try and figure this out. I think I may be getting closer.
public static void read()
String line;
StringTokenizer tokenizer;
String rate;
String term;
try
FileReader fr = new FileReader ("int&term.dat");
BufferedReader inFile = new BufferedReader (fr);
line = inFile.readLine();
while (line != null)
tokenizer = new StringTokenizer(line);
rate = tokenizer.nextToken();
line = inFile.readLine();
inFile.close();
System.out.println(new String());
catch (FileNotFoundException exception)
System.out.println ("The file was not found.");
catch (IOException exception)
System.out.println (exception);
}
Similar Messages
-
How do I read directly from file into byte array
I am reading an image from a file into a BuffertedImage then writing it out again into an array of bytes which I store and use later on in the program. Currently Im doing this in two stages is there a way to do it it one go to speed things up.
try
//Read File Contents into a Buffered Image
/** BUG 4705399: There was a problem with some jpegs taking ages to load turns out to be
* (at least partially) a problem with non-standard colour models, which is why we set the
* destination colour model. The side effect should be standard colour model in subsequent reading.
BufferedImage bi = null;
ImageReader ir = null;
ImageInputStream stream = ImageIO.createImageInputStream(new File(path));
final Iterator i = ImageIO.getImageReaders(stream);
if (i.hasNext())
ir = (ImageReader) i.next();
ir.setInput(stream);
ImageReadParam param = ir.getDefaultReadParam();
ImageTypeSpecifier typeToUse = null;
for (Iterator i2 = ir.getImageTypes(0); i2.hasNext();)
ImageTypeSpecifier type = (ImageTypeSpecifier) i2.next();
if (type.getColorModel().getColorSpace().isCS_sRGB())
typeToUse = type;
if (typeToUse != null)
param.setDestinationType(typeToUse);
bi = ir.read(0, param);
//ir.dispose(); seem to reference this in write
//stream.close();
//Write Buffered Image to Byte ArrayOutput Stream
if (bi != null)
//Convert to byte array
final ByteArrayOutputStream output = new ByteArrayOutputStream();
//Try and find corresponding writer for reader but if not possible
//we use JPG (which is always installed) instead.
final ImageWriter iw = ImageIO.getImageWriter(ir);
if (iw != null)
if (ImageIO.write(bi, ir.getFormatName(), new DataOutputStream(output)) == false)
MainWindow.logger.warning("Unable to Write Image");
else
if (ImageIO.write(bi, "JPG", new DataOutputStream(output)) == false)
MainWindow.logger.warning("Warning Unable to Write Image as JPEG");
//Add to image list
final byte[] imageData = output.toByteArray();
Images.addImage(imageData);
If you don't need to manipulate the image in any way I would suggest you just read the image file directly into a byte array (without ImageReader) and then create the BufferedImage from that byte array.
-
Reading .txt file into char array, file not found error. (Basic IO)
Iv been having some trouble with reading characters from a text file into a char array. I havnt been learning io for very long but i think im getting the hang of it. Reading and writing raw bytes
and things like that. But i wanted to try using java.io.FileReader to read characters for a change and im having problems with file not found errors. here is the code.
try
File theFile = new File("Mr.DocumentReadMe.txt");
String path = theFile.getCanonicalPath();
FileReader readMe = new FileReader(path);
char buffer[] = new char[(int)theFile.length()];
int readData = 0;
while(readData != -1)
readData = readMe.read(buffer);
jEditorPane1.setText(String.valueOf(buffer));
catch(Exception e)
JOptionPane.showMessageDialog(null, e,
"Error!", JOptionPane.ERROR_MESSAGE);
The error is: java.io.FileNotFoundException: C:\Users\Kaylan\Documents\NetBeansProjects\Mr.Document\dist\Mr.DocumentReadMe.txt (The system cannot find the file specified)
The text file is saved in the projects dist folder. I have tried saving it elsewhere and get the same error with a different pathname.
I can use JFileChooser to get a file and read it into a char array with no problem, why doesnt it work when i specify the path manually in the code?Well the file clearly isn't there. Maybe it has a .txt.txt extensionthat Windows is kindly hiding from you - check its Properties.
But:
String path = theFile.getCanonicalPath();
FileReader readMe = new FileReader(path);You don't need all that. Just:
FileReader readMe = new FileReader(theFile);And:
char buffer[] = new char[(int)theFile.length()];You don't need a buffer the size of the file, this is bad practice. Use 8192 or whatever.
while(readData != -1)
readData = readMe.read(buffer);
}That doesn't make sense. Read the data into the buffer and repeat until you get EOF? and do nothing with the contents of the buffer? The canonical read loop in Java goes like this:
while ((count = in.read(buffer)) > 0)
out.write(buffer, 0, count); // or do something else with buffer[0..count-1].
jEditorPane1.setText(String.valueOf(buffer));Bzzt. That won't give you the content of 'buffer'. Use new String(buffer, 0, count) at least. -
Reading large binary files into an array for parsing
I have a large binary log file, consisting of binary data separted by header flags scattered nonuniformly thorughout the data. The file size is about 50M Byte. When I read the file into an array, I get the Labview Memory full error. The design of this is to read the file in and then parse it fro the flags to determine where to separate the data blocks in the byte stream.
There are a few examples that I have read on this site but none seem to give a straight answer for such a simple matter. Does anyone have an example of how I should approach this?I agree with Gerd. If you are working with binaries, why not use U8 instead of doubles.
If the file is indeed 50MB, then the array should be expecting 52428800 elements, not 50000000. So if you read the file in a loop and populate an element at a time, you could run out of memory fast because any additional element insertion above 50000000 may require additional memory allocation of the size above 50000000 (potentially for each iteration). This is just speculation since I don't see the portion of your code that populates the array.
Question: Why do you need an array? What do you do with the data after you read it? I agree with Altenbach, 50MB is not that big, so working with a file of such a size should not be a problem. -
Reading one line from a text file into an array
i want to read one line from a text file into an array, and then the next line into a different array. both arays are type string...i have this:
public static void readAndProcessData(FileInputStream stream){
InputStreamReader iStrReader = new InputStreamReader (stream);
BufferedReader reader = new BufferedReader (iStrReader);
String line = "";
try{
int i = 0;
while (line != null){
names[i] = reader.readLine();
score[i] = reader.readLine();
line = reader.readLine();
i++;
}catch (IOException e){
System.out.println("Error in file access");
this section calls it:
try{
FileInputStream stream = new FileInputStream("ISU.txt");
HighScore.readAndProcessData(stream);
stream.close();
names = HighScore.getNames();
scores = HighScore.getScores();
}catch(IOException e){
System.out.println("Error in accessing file." + e.toString());
it gives me an array index out of bounds erroroh wait I see it when I looked at the original quote.
They array you made called names or the other one is prob too small for the amount of names that you have in the file. Hence as I increases it eventually goes out of bounds of the array so you should probably resize the array if that happens. -
How to read sampled data info from a "*.au"file into an array?
I need to manipulate the sound file directly using DSP, the first step is to read sampled data from "*.au" file into an array. How can I do that? Thanks a lot!!
There is a file I/O tutorial in the Java Tutorial (google for Java Tutorial). You can read an .au file as bytes like any binary file.
Or if you are using the Java Sound API, google for java sound api or java audio tutorial etc etc. -
so im new to this and having problems.
we have to read a .txt file into an array so when a user types a word in a text box it will search the file and reutrn found if the word is there and not found it the word is not there. but it is not reading the text file here is the code so far
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
public class Checker
// Declares Values in the array
static String [] anArray = new String[1000];
// declares variables needed in code later
int i;
String s;
static int count = 0;
static String b;
static JTextArea j = new JTextArea();
public void readFile() throws IOException{
File inFile = new File("words.txt");
FileReader fileReader = new FileReader(inFile);
BufferedReader bufReader = new BufferedReader(fileReader);
while (true){
b = bufReader.readLine();
anArray[count] = b;
count++;
if(b==null) throw new EOFException("Hello, end of file reached");
j.append(b);
j.append("\n");
// public static void main(String args[]){
// File outFile = new File("words.txt");
//FileOutputStream outFileStream = new FileOutputStream(outFile);
// PrintWriter outStream = new PrintWriter(outFileStream);
// outStream.println("help");
// File inFile = new File("words.txt");
// FileReader fileReader = new FileReader(inFile);
// BufferedReader bufReader = new BufferedReader(fileReader);
/* while (true){
b = bufReader.readLine();
anArray[count] = b;
count++;
if(b==null) throw new EOFException("Hello, end of file reached");
j.append(b);
j.append("\n");
public String checkword(String Word ) {
// Tries the code, runs through until an exception is found.
try {
for ( i = 0; i < anArray.length; i++)
if (Word.equals(anArray))
// If exception is found, throws a new exception
if (Word.equals(anArray[i])) throw new Exception(); // end if
} // end if
} // end for
} // end try
catch (Exception ae ) {
// if the word is found return a message found and its position in array.
return "Found, at position "+i;
}// end catch
// if its not in the array return a not found message
return "Not found";
} // end
} // end
and the gui class :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
public class CountDown extends JFrame implements ActionListener
// Defines the GUI components
private JTextField Word = new JTextField(9);
private JButton Guess = new JButton("Enter String");
private JLabel Message = new JLabel("not found");
// Creates a new instance of the Checker class.
Checker ch = new Checker();
public CountDown() // constructor
setTitle("Count Down");
setSize(300,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
Container c = getContentPane();
c.setBackground(Color.white);
c.setLayout(new GridLayout(3,1));
// Add the components
c.add(Word);
c.add(Guess);
c.add(Message);
c.add(ch.j);
// Add action Listener for Button to work
Guess.addActionListener(this);
pack();
setContentPane(c);
public void actionPerformed(ActionEvent e) {
// When the button is pressed do this code
if(e.getSource() == Guess)
// Looks in the checker class to compare the word user enters, to the words in the array.
// Returns a message if the word exists with its position in the list or
// Returns a message if the word does not exisit.
Message.setText( ch.checkword(Word.getText()));
public class CountDownA
public void main(String[] args)
CountDown Game = new CountDown();
any help is appriciated asapYuck! I echo jverd's sentiment. Please only post the specific pieces of code that you are having trouble with, and use the forum 'code' tags.
But to answer your question, I don't see where you're calling the readFile() method from. If you're not calling readFile, that might explain why nothing is being read.
As for the design of the readFile method, another 'yuck'. heh Don't use exceptions to break out of a loop. If you MUST break out of a loop, use break. But a loop like this doesn't need break. Try something like this:while( (b = bufReader.readLine()) != null)
anArray[count++] = b;
j.append(b+"\n");
}Also, in stead of creating an array of some arbitrary fixed length, I recommend using a collection class such as ArrayList.
In stead of this:static String [] anArray = new String[1000];
anArray[count++] = b;it would be better to use something like this:static ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add(b); -
Read from file and plot data against timestamp
Hello,
I know that there are already many posts regarding the question I m about to ask. But, I somehow dont seem to achieve what I want using the suggestions given in the other posts.
My problem is that, I have a file with the first column as a time stamp containing hour, minute, second and millisecond. The second column in a set of pressure values. I want to plot a graph of these pressure values against the timestamp recorded in this .txt file. Whatever I do, the timestamp values seem to skip by a couple of seconds.
How do i do this correctly?
Also, Is it advisable to use the read from file or the read from spreadsheet file vi? Kindly help me out.
Thanks and regards.Hey, I was having a similar issue the other day. The first problem I had was how to open the file and actually get the timestamp information. Since I'm using LabView 8.0, I had to go into Read Spreadsheet File and create a new vi to open strings (in an array form). That's the Read Spreadsheet File (string) vi below. Then, I had to figure out how to convert the string of a timestamp to something meaningful to me. The Timestamp2.vi is how I did that below. I'm also including a little test file. So, to run Timestamp2.vi, you will have to input the right base path, and have the Read Spreadsheet File (string).vi in the same place as Timestamp2. Hope that helps. I think I'm finally getting this stuff, so let me know if it doesn't work.
Attachments:
Test.txt 1 KB
Timestamp2.vi 28 KB
Read From Spreadsheet File (String).vi 25 KB -
How to read from file just the 2nd line onwards?
hi guys can anyone help me?
how to read from the file if the file was like this
2 2
2 1
1 3
and i want to get the 2 1 ,just the 2nd line and the 3rd line?
i tried using the string tokenizer but it kept saying
no such element
i tried this code:
StringTokenizer cols = new StringTokenizer(s," ");
temp = (String) (cols.nextElement());
num_rows = Integer.parseInt(temp);
temp = (String) (cols.nextElement());
num_cols = Integer.parseInt(temp);
matrix = new int [num_rows][num_cols];
// to add all the values in the data file into an array
while ( s!= null ) {
StringTokenizer st1 = new StringTokenizer (s);
while (st1.hasMoreTokens()){
for (i=0; i<num_rows; i++){
for (j=0; j<num_cols; j++)
matrix[i][j] = Integer.parseInt
( st1.nextToken());
} // whilecan anyone please help me?
thanksThis will read the file witout the first line:
import java.io.*;
import java.util.*;
public class Read2
public static void main (String[] args)
try
FileReader file = new FileReader("f.txt");
BufferedReader buff = new BufferedReader(file);
String line = buff.readLine();
while (line != null)
line = buff.readLine();
System.out.println(line);
buff.close();
catch(IOException e)
System.out.println("IO Error");
} Noah -
Getting file into an array of byte..
Hi guys,
i first thank you for all the help you've given in my precedent posts.
Now i've to ask you a question.
I need to convert some lines of a txt file(obtained from an excel table) into an array of byte in the best possible manner.
My file can have a various number of rows and columns.
With this code
BufferedReader br = new BufferedReader(new InputStreamReader(myFile.getInputStream()));
String line = null;
while ((line = br.readLine()) != null) {
line = line.replace (',', '.');
StringTokenizer st = new StringTokenizer(line);
numberOfNumericColumns = (st.countTokens()-1);
col=(numberOfNumericColumns+1);I read the file, i change , with . and line to line i calculate the number of value(that have to be the same,i do the control for showing exception if necessary).
Now i know from my file what are the number of values in a row(columns of my old excel table).
I have to convert this file into an array of byte.
How can i do it?
Suppose we have only 3 lines, the first line is ever only string,the others lines have a string and other double values.....
nome giuseppe carmine paolo
valerio 23.3 34.3 43.3
paolo 21.2 34.5 12.2
each value is separated from another one by one or more whitespaces..
The most important thing is that in a second moment i have to read this array of byte and showing its original content,so i have to put in the array some different value and different line symbol delimiter.
Can you help me giving me some idea or code?(please be clear,i'm inexpert of java...)
Thanks very much,i need your help
Message was edited by:
giubatthanks for your reply...
my file has about 50000 rows..........and i have to develop an application that allows the upload of about 6000/7000 files....
so i have to optimize everythings......i want to use whitespace to separate different value and ;different line
so in my array of bytes i want
nome(converted in byte) whitespace(in byte) giuseppe (in byte) whitespace(in byte)carmine(in byte) whitespace(in byte) paolo (in byte) ;(in byte);
valerio(in byte) whitespace(in byte) 23.3 (in byte) whitespace(in byte) 34.3 (in byte) whitespace(in byte)43.3 (in byte) ;(in byte) etc.....So i should have an array of byte lower than the array of byte obtained converting each line as a string into bytes.......
do you understand what's my problem?
How can i create an array of byte without fixing its initial dimension that is able to grows up for each line read?
Excuse for my poor english..
In the past i've used a vector to temporary store the data while reading the file and at the end i copied the vector in the array of byte but when i do upload in my application i had java heap size error.
So someone has suggested me to improve my storing method and i've decided to eliminate vector....
can you help me......????
please....i need your help.. -
Question about reading csv file into internal table
Some one (thanks those nice guys!) in this forum have suggested me to use FM KCD_CSV_FILE_TO_INTERN_CONVERT to read csv file into internal table. However, it can be used to read a local file only.
I would like to ask how can I read a CSV file into internal table from files in application server?
I can't simply use SPLIT as there may be comma in the content. e.g.
"abc","aaa,ab",10,"bbc"
My expected output:
abc
aaa,ab
10
bbb
Thanks again for your help.Hi Gundam,
Try this code. I have made a custom parser to read the details in the record and split them accordingly. I have also tested them with your provided test cases and it work fine.
OPEN DATASET dsn FOR input IN TEXT MODE ENCODING DEFAULT.
DO.
READ DATASET dsn INTO record.
PERFORM parser USING record.
ENDDO.
*DATA str(32) VALUE '"abc",10,"aaa,ab","bbc"'.
*DATA str(32) VALUE '"abc","aaa,ab",10,"bbc"'.
*DATA str(32) VALUE '"a,bc","aaaab",10,"bbc"'.
*DATA str(32) VALUE '"abc","aaa,ab",10,"b,bc"'.
*DATA str(32) VALUE '"abc","aaaab",10,"bbc"'.
FORM parser USING str.
DATA field(12).
DATA field1(12).
DATA field2(12).
DATA field3(12).
DATA field4(12).
DATA cnt TYPE i.
DATA len TYPE i.
DATA temp TYPE i.
DATA start TYPE i.
DATA quote TYPE i.
DATA rec_cnt TYPE i.
len = strlen( str ).
cnt = 0.
temp = 0.
rec_cnt = 0.
DO.
* Start at the beginning
IF start EQ 0.
"string just ENDED start new one.
start = 1.
quote = 0.
CLEAR field.
ENDIF.
IF str+cnt(1) EQ '"'. "Check for qoutes
"CHECK IF quotes is already set
IF quote = 1.
"Already quotes set
"Start new field
start = 0.
quote = 0.
CONCATENATE field '"' INTO field.
IF field IS NOT INITIAL.
rec_cnt = rec_cnt + 1.
CONDENSE field.
IF rec_cnt EQ 1.
field1 = field.
ELSEIF rec_cnt EQ 2.
field2 = field.
ELSEIF rec_cnt EQ 3.
field3 = field.
ELSEIF rec_cnt EQ 4.
field4 = field.
ENDIF.
ENDIF.
* WRITE field.
ELSE.
"This is the start of quotes
quote = 1.
ENDIF.
ENDIF.
IF str+cnt(1) EQ ','. "Check end of field
IF quote EQ 0. "This is not inside quote end of field
start = 0.
quote = 0.
CONDENSE field.
* WRITE field.
IF field IS NOT INITIAL.
rec_cnt = rec_cnt + 1.
IF rec_cnt EQ 1.
field1 = field.
ELSEIF rec_cnt EQ 2.
field2 = field.
ELSEIF rec_cnt EQ 3.
field3 = field.
ELSEIF rec_cnt EQ 4.
field4 = field.
ENDIF.
ENDIF.
ENDIF.
ENDIF.
CONCATENATE field str+cnt(1) INTO field.
cnt = cnt + 1.
IF cnt GE len.
EXIT.
ENDIF.
ENDDO.
WRITE: field1, field2, field3, field4.
ENDFORM.
Regards,
Wenceslaus. -
Dear friends,
I have one problem. When we are creating abap program by clicking on program button on recording screen it asks for the program name and there are 2 oprions..
1) read from file and
2)transfer from recording....second one is fine...but i am not able to use first option...how to use that and why it is used...
Thanks And Regards,
Bhavin Shah.Hi Bhavin,
The basic difference between read from file & transfer from recording is that...
In transfer from recording you have to give a session name or you have to choose call transaction. Here you have to give the data manually.
The Read from file will generate a dataset where who have to give that path of your flat file. When you execute it the data from the flat file will go into the necessary fields you have choosen before. You can process the job in the back ground which will be executed and a log file will be generated so that you can check whether it is updated correctly or not.
In general we use read from file option when we know that the data are correctly arranged for recording.
For eg. if you want to update the database with the file you have to know the datatype and length of each database-field so that you can specify the data in a file.
i.e Assume that you are having 2 fields in db-table of type char and length 10 & 20. Assume that you are going to give values for these fields as mala & kala.
In the file... you should specify like this...
mala kala xxx
123456789012345678901234567890
<---Ten--><-----Twenty------->
In a Real Time scenario you have a very large table with 50 to 100 fields to update with a very large data like 1000 - 10,000 records and if you are not sure with the flat file data. Then you should not go for the file option.
Hope this helps you.
Regards,
Maheswaran.B -
Get the content of a file into a array
Hy to all!I have txt file with the following content : 0 1 1 0
1 1 1 0
0 0 0 0. I want to extract the values to a bi-dimension array,like this: a[0][0] = 0,a[0][1] = 1,a[0][2] = 1....and so on.
Anybody could give a little help.THXThe first thing I can help you with is that this doesn't have anything to do with java serialization.
Secondly, if you are new to java, the best forum is "New To Java" forum.
Thirdly, make sure you have done a google search first for an answer because it is likely that many people have asked the same question before.
The follow search gets over 2 million hits. [http://www.google.co.uk/search?q=java+read+content+of+a+file+into+a+array] -
Error reading from file glibc-2.5-24.i686.rpm RHEL 5 Setup stuck at 80%
Hi, I am installing Oracle 10g on RHEL 5 (Red Hat Enterprise Linux 5) machine I am facing two problems
1) while installing the rpm packages the following package gave an error
Error reading from file glibc-2.5-24.i686.rpm
2) I still gave a try to runInstaller command the installer opened but was stuck at 80%
I have 3 GB ram and 320GB hard drive I am not sure what to put in the swap memory and other settings i blindly followed instructions given here
http://www.oracle-base.com/articles/10g/OracleDB10gR2InstallationOnRHEL5.php
What could be the problem where do I find the error log if its created
Please help me
Thanks
Edited by: 891355 on Nov 6, 2011 12:06 PMI found the installActions file in the installer folder and I think this could be the problem
INFO: The 'shiphomeproperties.xml' file is missing from shiphome location '/home/oracle/Desktop/database/install/../stage/products.xml.' Add this file to the 'Disk1/stage' directory of the shiphome.
though I am attaching the log file for more details do you think the installer is corrupt :(
InstallActions log file ==> http://www.mediafire.com/?nh7mx7bxqht9ovu
Edited by: 891355 on Nov 6, 2011 1:35 PM -
Hi all
I'm trying to install SQL 2008 Express on my Computer: Hp compact DX7300 Slim tower.
and get this error:
TITLE: Microsoft SQL Server 2008 Setup
The following error has occurred:Error reading from file d:\8268cd7b247d294de359c9\x86\setup\sql_engine_core_inst_msi\PFiles\SqlServr\MSSQL.X\MSSQL\Binn\Template\msdbdata.mdf. Verify that the file exists and that you can access it.
Click 'Retry' to retry the failed action, or click 'Cancel' to cancel this action and continue setup.
For help, click: http://go.microsoft.com/fwlink?LinkID=20476&ProdName=Microsoft+SQL+Server&EvtSrc=setup.rll&EvtID=50000&ProdVer=10.0.1823.0&EvtType=0xF45F6601%25401201%25401
Log file
Overall summary:
Final result: SQL Server installation failed. To continue, investigate the reason for the failure, correct the problem, uninstall SQL Server, and then rerun SQL Server Setup.
Exit code (Decimal): -2068643839
Exit facility code: 1203
Exit error code: 1
Exit message: SQL Server installation failed. To continue, investigate the reason for the failure, correct the problem, uninstall SQL Server, and then rerun SQL Server Setup.
Start time: 2014-12-09 23:22:03
End time: 2014-12-09 23:40:28
Requested action: Install
Log with failure: C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log\20141209_232121\sql_engine_core_inst_Cpu32_1.log
Exception help link: http://go.microsoft.com/fwlink?LinkId=20476&ProdName=Microsoft+SQL+Server&EvtSrc=setup.rll&EvtID=50000&ProdVer=10.0.1823.0
Machine Properties:
Machine name: VISTA-PC
Machine processor count: 2
OS version: Windows Vista
OS service pack: Service Pack 1
OS region: United States
OS language: English (United States)
OS architecture: x86
Process architecture: 32 Bit
OS clustered: No
Product features discovered:
Product Instance Instance ID Feature
Language Edition Version Clustered
Package properties:
Description: SQL Server Database Services 2008
SQLProductFamilyCode: {628F8F38-600E-493D-9946-F4178F20A8A9}
ProductName: SQL2008
Type: RTM
Version: 10
SPLevel: 0
Installation location: d:\8268cd7b247d294de359c9\x86\setup\
Installation edition: EXPRESS
User Input Settings:
ACTION: Install
ADDCURRENTUSERASSQLADMIN: False
AGTSVCACCOUNT: NT AUTHORITY\NETWORK SERVICE
AGTSVCPASSWORD: *****
AGTSVCSTARTUPTYPE: Disabled
ASBACKUPDIR: Backup
ASCOLLATION: Latin1_General_CI_AS
ASCONFIGDIR: Config
ASDATADIR: Data
ASDOMAINGROUP: <empty>
ASLOGDIR: Log
ASPROVIDERMSOLAP: 1
ASSVCACCOUNT: <empty>
ASSVCPASSWORD: *****
ASSVCSTARTUPTYPE: Automatic
ASSYSADMINACCOUNTS: <empty>
ASTEMPDIR: Temp
BROWSERSVCSTARTUPTYPE: Disabled
CONFIGURATIONFILE: C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log\20141209_232121\ConfigurationFile.ini
ENABLERANU: True
ERRORREPORTING: False
FEATURES: SQLENGINE,REPLICATION
FILESTREAMLEVEL: 0
FILESTREAMSHARENAME: <empty>
FTSVCACCOUNT: <empty>
FTSVCPASSWORD: *****
HELP: False
INDICATEPROGRESS: False
INSTALLSHAREDDIR: C:\Program Files\Microsoft SQL Server\
INSTALLSHAREDWOWDIR: C:\Program Files\Microsoft SQL Server\
INSTALLSQLDATADIR: <empty>
INSTANCEDIR: C:\Program Files\Microsoft SQL Server\
INSTANCEID: SQLExpress
INSTANCENAME: SQLEXPRESS
ISSVCACCOUNT: NT AUTHORITY\NetworkService
ISSVCPASSWORD: *****
ISSVCSTARTUPTYPE: Automatic
MEDIASOURCE: d:\8268cd7b247d294de359c9\
NPENABLED: 0
PID: *****
QUIET: False
QUIETSIMPLE: False
RSINSTALLMODE: FilesOnlyMode
RSSVCACCOUNT: <empty>
RSSVCPASSWORD: *****
RSSVCSTARTUPTYPE: Automatic
SAPWD: *****
SECURITYMODE: <empty>
SQLBACKUPDIR: <empty>
SQLCOLLATION: SQL_Latin1_General_CP1_CI_AS
SQLSVCACCOUNT: NT AUTHORITY\NETWORK SERVICE
SQLSVCPASSWORD: *****
SQLSVCSTARTUPTYPE: Automatic
SQLSYSADMINACCOUNTS: VISTA-PC\VISTA
SQLTEMPDBDIR: <empty>
SQLTEMPDBLOGDIR: <empty>
SQLUSERDBDIR: <empty>
SQLUSERDBLOGDIR: <empty>
SQMREPORTING: False
TCPENABLED: 0
X86: False
Configuration file: C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log\20141209_232121\ConfigurationFile.ini
Detailed results:
Feature: Database Engine Services
Status: Failed: see logs for details
MSI status: Passed
Configuration status: Passed
Feature: SQL Server Replication
Status: Failed: see logs for details
MSI status: Passed
Configuration status: Passed
Rules with failures:
Global rules:
Scenario specific rules:
Rules report file: C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log\20141209_232121\SystemConfigurationCheck_Report.htm
I will very appriciate if someone can help me solve it. I was trying to set Full control for my account in Properties/Security of root folder and try again but error is still.
Many thanksHi Foreverduy,
Before you run SQL Server 2008 express setup, make sure that you have installed Windows installer 4.5 and.NET Framework 3.5 SP1 manually. For more information about the process, please refer to the article:
http://msdn.microsoft.com/en-us/library/ms143506(v=sql.100).aspx. Moreover, please turn off all the third-party softwares which could prohibit the installation process.
According to your error message, the issue could be due to that your account has no rights to install SQL Server, or the corruption on the media.
Firstly, please ensure that your account has admin rights. Also make sure that you right-click the setup.exe and choose “Run as administrator” to complete the installation.
Secondly, please check if "msdbdata.mdf" file exists at d:\8268cd7b247d294de359c9\x86\setup\sql_engine_core_inst_msi\PFiles\SqlServr\MSSQL.X\MSSQL\Binn\Template. If it exists, please make sure that your account has read permission to the extracted
folder.
However, if the file doesn't exist in the extraction, the media could be corrupt. Please download the
media
again and check if the issue still occurs.
Regards,
Michelle Li
Maybe you are looking for
-
I am using an Mac PPC version 10.5.8 and I am trying to download the correct version of Flash Player. I did once but I had to install a "Clean Install" of my computer and when finished I had put back the new Flash Player I just installed well every
-
Importing a class in a project
Hi. I wrote a class I would like to use in many projects. I've never had such a need, so I don't know whether it is possible or not to import it or not. I would like to place this class in a directory, and leave it there. Then, when writing some othe
-
Adobe Dreamweaver CS3 has shopped working
In the past two days I have been getting the following error message when I try to make changes to an open page in Dreamweaver CS3: "Adobe Dreamweaver CS3 has stopped working" "A problem caused the program to stop working correctly. Windows will clos
-
Hi Have just purchased a Mustek ScanExpress A# USB 2400 Por and cant seem to install it. I'm on a 2.4ghz imac running 10.6.8. I'm on image acquire, have installed the drivers for this os, the scanner name appears in the ImageAcquire drop down box, bu
-
How to lock the month in Planning web forms
Hi all , we r using the web forms in planning for inputting the data . we had a problem here. ex: User is giving the in put for the month Dec..and again in he is changing the data..so how to lock the in web forms month wise. thanks in Adv