Reading content of a file into an int array
How do i use FileReader rd = new FileReader(filename) to read the contents into an int array?
public static int[] parse_file(String filename)
Vector vec = new Vector();
int num[];
num = new num[vec.size()];
try {
BufferedReader br = new BufferedReader(new FileReader(filename));
String line;
while((line = br.readLine()) != null) {
vec.add(line);
for (int i = 0; i < vec.size(); i++) {
num[i] = (int) vec.get(i);
System.out.println("Number=" + num);
catch(IOException e) {
System.out.println("error");
return num;
Maxsum.java:22: cannot resolve symbol
symbol : class num
location: class Maxsum
num = new num[vec.size()];
^
Maxsum.java:30: inconvertible types
found : java.lang.Object
required: int
num[i] = (int) vec.get(i);
How do i initialize the array?if i do not initialize it, there'll be array not initialized error also..How do i convert the String to int?
Similar Messages
-
Problem with reading numbers from file into double int array...
Okay, this is a snippet of my code:
public void readMap(String file){
try {
URL url = getClass().getResource(file);
System.out.println(url.getPath());
BufferedReader in = new BufferedReader(new FileReader(url.getPath()));
String str;
String[] temp;
int j=0;
while ((str = in.readLine()) != null) {
temp = str.split(",");
for(int i=0;i<temp.length;i++){
map[j] = java.lang.Integer.parseInt(temp[i]);
j++
in.close();
} catch (IOException e) {
System.out.println("Error: "+ e.toString());
map[][] is a double int array. Now, the code is running through each line of the text file (with each line looking like this: 0,3,6,2,2,3,1,5,2,3,5,2), and I want to put the numbers into a corresponding double int array (which is where map[][] comes in). Now, this code WOULD work, except I need to set the sizes of each array before I start adding, but I don't know how to get the exact sizes.. how can I get around this issue?
Message was edited by:
maxfarrarYou can do a two-dimensional ArrayList? That syntax
you wrote didn't work.
I tried doing:
private ArrayList<ArrayList><Integer>> map;
Your syntax is just wrong -- or, this forum software has bug in handling angle brackets.
ArrayList<ArrayList<Integer>>...The closing angle bracket after the second 'ArrayList' is the one generated by the bug. Basically, it should be T<T<T2>> without spaces. Oh, for that matter:
Arraylist<ArrayList<Integer>> -
Reading from a text file into a 2D array
How do you read from a text file and put it into a 2D array? Or if someone could guide me to where I can find the information?
This tutorial shows how to read a file:
http://java.sun.com/docs/books/tutorial/essential/io/scanfor.html
This tutorial shows how to create arrays with multiple dimensions:
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.html -
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] -
How to read a whole text file into a pl/sql variable?
Hi, I need to read an entire text file--which actually contains an email message extracted from a content management system-- into a variable in a pl/sql package, so I can insert some information from the database and then send the email. I want to read the whole text file in one shot, not just one line at a time. Shoud I use Utl_File.Get_Raw or is there another more appropriate way to do this?
how to read a whole text file into a pl/sql variable?
your_clob_variable := dbms_xslprocessor.read2clob('YOUR_DIRECTORY','YOUR_FILE');
.... -
Read contents inside pdf file programmatically in SharePoint
I have a SharePoint document library, My Requirement is when user add PDF file on the document library the event receiver fire and read contents inside
pdf file programmatically. After the start workflow according to the result of event receiver.If your question is about handling events in apps for SharePoint, see these links:
http://msdn.microsoft.com/en-us/library/office/jj220048%28v=office.15%29.aspx
http://msdn.microsoft.com/en-us/library/office/jj220051%28v=office.15%29.aspx
If what you need is a way to extract text from the PDF inside the event handler, see this example that uses leadtools.
http://support.leadtools.com/CS/forums/ShowPost.aspx?PostID=43894
You should use PDF text extractor in your Event Handler code -
You can use iTextSharp for reading content
http://www.codeproject.com/Tips/387327/Convert-PDF-file-content-into-string-using-Csharp -
To read data from exel file into sap
hi all,
How to read data from exel file into the internal table in abap?
Regards,
sugeet.Hi Sugeet,
Use the following code.
DATA : BEGIN OF tbl_asset occurs 0,
anlkl LIKE anla-anlkl, " Asset Class
bukrs LIKE anla-bukrs, " Company Code
ranl1 LIKE ra02s-ranl1, " Asset #
txt50 LIKE anla-txt50, " Description 1
txa50 LIKE anla-txa50, " Description 2
sernr LIKE anla-sernr, " Serial #
invnr LIKE anla-invnr, " Inventory #
menge LIKE anla-menge, " Quantity
meins LIKE anla-meins, " Base UOM
inken LIKE anla-inken, " Inventory
END OF tbl_asset.
DATA : w_filename TYPE IBIPPARMS-path,
w_file TYPE string.
start-of-selection.
*popup for file path from user
CALL FUNCTION 'F4_FILENAME'
EXPORTING
PROGRAM_NAME = SYST-CPROG
DYNPRO_NUMBER = SYST-DYNNR
IMPORTING
FILE_NAME = w_filename .
MOVE w_filename TO w_file .
* upload data
CALL FUNCTION 'GUI_UPLOAD'
EXPORTING
FILENAME = w_file
FILETYPE = 'ASC'
HAS_FIELD_SEPARATOR = 'X'
TABLES
DATA_TAB = tbl_asset
EXCEPTIONS
FILE_OPEN_ERROR = 1
FILE_READ_ERROR = 2
NO_BATCH = 3
GUI_REFUSE_FILETRANSFER = 4
INVALID_TYPE = 5
NO_AUTHORITY = 6
UNKNOWN_ERROR = 7
BAD_DATA_FORMAT = 8
HEADER_NOT_ALLOWED = 9
SEPARATOR_NOT_ALLOWED = 10
HEADER_TOO_LONG = 11
UNKNOWN_DP_ERROR = 12
ACCESS_DENIED = 13
DP_OUT_OF_MEMORY = 14
DISK_FULL = 15
DP_TIMEOUT = 16
OTHERS = 17
IF SY-SUBRC <> 0.
* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
* WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF.
for HAS_FIELD_SEPARATOR Use
'X': Fields are separated by tabs.
SPACE: Fields are not separated by tabs. In this case, the table must contain only one column or all columns must be contained in the file in their entire length.
Hope it helps...
Lokesh
Pls. reward appropriate points -
How to copy data in text file into two-dimensional arrays?
Greeting. Can somebody teach me how to copy the input file into two-dimensional arrays? I'm stuck in making a matrix with number ROWS and COLUMNS according to the data in "input.txt"
import java.io.*;
import java.util.*;
public class array
public static void main (String[] args) throws FileNotFoundException
{ Scanner sc = new Scanner (new FileReader("input.txt"));
PrintWriter outfile = new PrintWriter("output.txt");
int[][]matrix = new int[ROWS][COLUMNS];
}my input.txt :
a,b,c
2,2,1
1,1,1
2,2,1
3,3,1
4,4,1
5,5,1
1,6,2
2,7,2
3,8,2
4,9,2
5,10,2import java.io.*;
import java.util.*;
public class array {
public static void main(String[] args) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("input.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null) {
String split[]=line.split(",");
catch (IOException x) {
System.err.println(x);
} finally {
if (in != null) in.close();
}}}What after this? -
Reading a text data file into memory
hi,
I have a text file which contains data, The text file is parsed and objects are created. The problem is the text file is quite huge measuring upto 1.8~2 Mb. The format of the text file is as follows
Units: METRIC (atm, m3)
* Step: 1 Time: 0.00
* Average Field Pressure : 204.14
* Region 1 Pressure : 204.14
Well GROUP Layer Blk_Pressure BHP ResRate OilRate WaterRate GasRate KhProd Windex PindeWELLTYPE
1 FIELD 1 204.14 49.33 6601.22 6568.10 37.14 538.07 99999.00 260.35 99999.00 P
1 FIELD 2 204.14 50.34 6558.13 6525.23 36.90 534.56 99999.00 260.35 99999.00 P
1 FIELD 3 204.14 51.35 6515.04 6482.36 36.65 531.04 99999.00 260.35 99999.00 P
1 FIELD Tot 204.14 50.34 19674.40 19575.69 110.69 1603.67 99999.00 99999.00 99999.00 P
2 FIELD 1 204.14 377.66 7573.96 0.00 7403.68 0.00 99999.00 260.35 99999.00 I
2 FIELD 2 204.14 378.40 7606.33 0.00 7435.32 0.00 99999.00 260.35 99999.00 I
2 FIELD 3 204.14 379.14 7638.70 0.00 7466.96 0.00 99999.00 260.35 99999.00 I
2 FIELD Tot 204.14 378.40 22818.99 0.00 22305.95 0.00 99999.00 99999.00 99999.00 I
* Step: 2 Time: 20.23
* Average Field Pressure : 300.11
* Region 1 Pressure : 300.11
Well GROUP Layer Blk_Pressure BHP ResRate OilRate WaterRate GasRate KhProd Windex PindeWELLTYPE
1 FIELD 1 194.20 49.33 858.83 853.40 5.36 68.22 99999.00 260.35 99999.00 P
1 FIELD 2 194.48 50.34 871.71 866.22 5.42 69.35 99999.00 260.35 99999.00 P
1 FIELD 3 194.76 51.35 884.86 879.29 5.48 70.49 99999.00 260.35 99999.00 P
1 FIELD Tot 194.48 50.34 2615.40 2598.91 16.26 208.06 99999.00 99999.00 99999.00 P
2 FIELD 1 370.40 377.66 912.25 0.00 891.74 0.00 99999.00 260.35 99999.00 I
2 FIELD 2 371.26 378.40 895.75 0.00 875.61 0.00 99999.00 260.35 99999.00 I
2 FIELD 3 372.12 379.14 879.29 0.00 859.52 0.00 99999.00 260.35 99999.00 I
2 FIELD Tot 371.26 378.40 2687.28 0.00 2626.86 0.00 99999.00 99999.00 99999.00 I
The Step goes on till like 3000, I am creating an object for each step which inturn has nested object for each well and the well in turn for each layer. In the above case of step 3 the object would be
class Step 2{
inner class well
{ //for well 1
inner class layer { // for layer 1 }
inner class layer {/ for layer 2 }
inner class layer {/ for layer 3 }
inner class well
{ //for well 2
inner class layer { // for layer 1 }
inner class layer {/ for layer 2 }
inner class layer {/ for layer 3 }
This architecture of mine is proving to be heavy as I would end up with around 9000 Java objects in memory, though my classes only have have int, float, String data items. I am using this data to plot graphs, so I guess it wouldnt be optimal to read data from text file for each plot.
So in short the problem is can anyone tell a better way to read the data into memory ? given that there could be 3000 steps in the format given above.
Thanks
AMI have implemented and it takes around 30-45 sec to parse and also the GUI has become very slow. I query the objects for multiple combinations of graphs.
The data from the objects is being used to feed the graphs on my GUI. I have a number of options on my GUI for different kinds of graphs, for each combination chosen the Objects are queried for the data. The GUI is written using Swing.
So is there anyway I can fine tune the application, any tips about the object architecture or how to improve the speed. I am also explicitly running the garbage collector a few times in my program. Also how can I make JVM occupy lesser memory so that my program can have more memory.
Thanks
am -
Move the contents of old file into another before writing in applcn srvr
Hi Friends,
As per the requirement I need to move the contents of the previous file into an archieve folder which is being created by the previous run of the program in the application server.
After the old file has been moved I need to craete the new file in the directory.
So at any time only one file should be present in the application server.
All the previous files will be in the Archieve folder.
Please suggest how can I move the contents of the privious file in the archieve directory.
Thanks and regards,
Smriti Singh
Please do not duplicate post
Edited by: Rob Burbank on Feb 24, 2009 11:16 AMHi Smriti,
check this
1) use the function module 'EPS_GET_DIRECTORY_LISTING' --- to gett the details of files n application dir
eq.
call function 'EPS_GET_DIRECTORY_LISTING'
exporting
dir_name = p_file
tables
dir_list = it_dir_list
exceptions
invalid_eps_subdir = 1
sapgparam_failed = 2
build_directory_failed = 3
no_authorization = 4
read_directory_failed = 5
too_many_read_errors = 6
empty_directory_list = 7
others = 8.
if sy-subrc <> 0.
message id sy-msgid type sy-msgty number sy-msgno
with sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
endif.
2) then use this code to archive
open dataset w_file1 for output in text mode encoding default. "Open Backup File
if sy-subrc <> 0.
write: /1 ' error creating file with status - ', sy-subrc.
exit.
endif.
open dataset w_dirname for input in text mode encoding default."Open Real File
if sy-subrc <> 0.
error_flag = 'X'.
write: /1 ' error opening input file with status - ', sy-subrc.
exit.
endif.
*" To read the input file into a internal table
do.
read dataset w_dirname into inrec_lpcfab.
if sy-subrc <> 0.
exit.
else.
if not inrec_lpcfab is initial.
append inrec_lpcfab.
transfer inrec_lpcfab to w_file1 length 180.
endif.
endif.
enddo.
close dataset w_dirname. -
Read words from a text file into an undefined array
Dear all,
Does anyone know how to read words in text file, seperated by all types of spaces ("_", "\n", "\t","\r","\f") and put them into a string array to be used later?
So far I can read the words using the Tokenizer but can't assign to array:
public class reader
StringTokenizer tokenizer = new StringTokenizer(input);
String[ ] array= null; //unknown size of array
int i=0;
while(tokenizer.hasMoreTokens())
array[i] = tokenizer.nextToken();
i++;
Any suggestions welcome!
thanks in advance!Hi
sorry wrote in a hurry ;) din c the problem clearly
there are two approaches
1) best approach for your problem is Vector or ArrayList, these would make life easy for you.
Always collections are better approach over arrays when the size is dynamic. However in your case the size cant be said to be DYNAMIC. coz the number of words will not grow / shrink during the runtime.. i know that number of words are not fixed but dynamic is something which will grow/shrink during runtime. but still collection is better approach.
2)dirty approach
use double dimensional array
String arr[][] = null;
then use one tokenizer for StringTokenizer(str,"\n");
using countTokens on this will give you number of lines.
use this to initialize array
arr = new String[lineCount][];
then iterate from 1 to lineCount and use 1 more tokenizer to get number of words for that line. use this number to initialize the column size for arr[i] like
arr[i] = new String[wordCount];
then store the token using nested for loops in this array
go for the 1st one ;) 2nd one is hedious n time consuming but both will work ;)
cheers
amey -
How to save the contents of one file into another file?
Hai,
i'm trying to save the contents of an existing file into a new file...
for example.. if i'm having a ms word file namely ss.doc..
now i want to save itz contents into another file namele dd.doc..
How shall i do it..
Can an one plzz explain me...
senthil.Hi, Senthil.
This Forum is not a general discussion forum.
You don't believe that the InDesign SDK is a general purpose API. Do you?
I think you must post issues like this where they belong, in this case in a Microsoft Word Forum.
Best regards.
Oscar. -
How can I read content from PDF file stored in Oracle 9i XMLDB
Hi Friends:
Now I have met one question that I don`t know how to read some String , for example "Hello", from the PDF file stored in the Oracle 9i XMLDB, I have stored that PDF file into the XMLDB now, any suggestions are appriciated . Thank you in advance.You may be able to do something with Oracle Text. The following shows how to get an HTML rendiditon of a binary document. I think you can also get plain text instead of HTML
set echo on
spool xfilesUtilties.log
connect sys/&1 as sysdba
grant ctxapp to &2
connect &2/&3
begin
ctxsys.ctx_ddl.create_policy(policy_name=>'XFILES_HTML_GENERATION', filter=>'ctxsys.auto_filter');
end;
create or replace package xfiles_internal_11010
authid definer
as
function renderAsHTML(sourceDoc BLOB) return CLOB;
end;
show errors
create or replace package body xfiles_internal_11010
as
function renderAsHTML(sourceDoc BLOB)
return CLOB
as
html_content CLOB;
begin
dbms_lob.createTemporary(html_content,true,DBMS_LOB.SESSION);
ctx_doc.policy_filter(policy_name => 'XFILES_HTML_GENERATION',
document => sourceDoc,
restab => html_content,
plaintext => false);
return html_content;
end;
end;
show errors
create or replace package xfiles_utilities_11010
authid current_user
as
HOME_FOLDER constant varchar2(700) := xdb_constants.HOME_FOLDER;
PUBLIC_FOLDER constant varchar2(700) := xdb_constants.PUBLIC_FOLDER;
function renderAsHTML(sourceFile VARCHAR2) return CLOB;
function transformToHTML(xmldoc XMLType, xslPath VARCHAR2) return CLOB;
end;
show errors
create or replace package body xfiles_utilities_11010
as
function renderAsHTML(sourceFile VARCHAR2)
return CLOB
as
begin
return xfiles_internal_11010.renderAsHTML(xdburitype(sourceFile).getBLOB());
end;
function transformToHTML(xmldoc XMLType, xslPath VARCHAR2)
return CLOB
as
html clob;
begin
select xmldoc.transform(xdburitype(xslPath).getXML()).getClobVal()
into HTML
from dual;
return html;
end;
end;
show errors
grant execute on xfiles_utilities_11010 to public
create or replace public synonym xfiles_utilities for xfiles_utilities_11010
quitMessage was edited by:
mdrake -
Read file into multi-dimensional array - ideal world...
Hello all, would be very grateful if you could help me...
I have a file which has a format...
string1a,string1b
string2a,string2bi need to read this file, which will have a variable length, into a two dimensional array.
the code below is just demonstrating my approach...
List lines = new ArrayList();
BufferedReader in = new BufferedReader(new FileReader(filename));
String str;
while ((str = in.readLine()) != null) {
lines.add(str.split(","));
in.close();but when i later try and invoke the toArray() method of lines it complains about unsafe or unchecked operations.
does any have any pointers about the best way to read a file into a multi-dimensional array? is it best practice to use the interface List?
thanks in advance
poncenbyThis is just a List of Lists - no worries there.
Sounds like your toArray code is incorrect. Post that.
% -
How to copy the content of one file into another
I have tried this code
try {
fin = new FileInputStream("file path");
catch(FileNotFoundException exc)
System.out.println("File not found");
return 0;
catch(ArrayIndexOutOfBoundsException exc)
System.out.println("Usage: Showfile file");
return 0;
while(true){
i=fin.read();
if(i==-1)
break;
cnt++;
fin.close();*/
now in this way i can lift one character at a time and copy it into another file (note i have not done the copy part in this code but that can be implemented) however this whole procedure is taking too much time if the size of the file is too big....kindly suggest another way to copy one file into anotherhave you ever copied and pasted a large file in Windows or another OS? Larger files take more time to copy, that's just how it is.
Maybe you are looking for
-
my wife and i both have an itunes library installed on to our separate pc's, we are now de-commissioning the pc's and are moving over to a single mac mini, can we install both libraries on to the mac mini and run them as separate libraries?
-
HP laserJet 5200dtn making buzzing/humming noise after printing
Hi, We have about three of these units in our office and one of them has recently began to make a loud buzzing/humming noise during and after printing a document. THe noise last about 5-10 seconds after the print job completes. I can also make the p
-
TS3276 Attach a document as a file and not in the body of the email
Good Morning from the UK! I have recently changed over from using MS Office for emails and onto Apple Email I now cannot attach documents in an email as a file They appear in the body of the email The recipient cannot view them as they are too small
-
XSLT - How to pass a Java object to the xslt file ?
Hi , I need help in , How to pass a java object to xslt file. I am using javax.xml.transform.Tranformer class to for the xsl tranformation. I need to pass a java object eg Class Employee { private String name; private int empId; public String getName
-
Podcasts show as already submitted
I recently had 3 podcasts removed from your iTunes store because I am changing the feed and, since I can't edit or change the source code on the prior feed (at Mevio), I had to have them canceled/removed, with the intent to resubmit them. All three p