Android: Reading doubles from a textfile and put them in an array - java

I am trying to read values from a text file. There are 6 doubles on each line for the file.
I created a getBufReader method
public BufferedReader getBufReader(String filename, int rawName){
if(D) Log.i(TAG, "GETTING FILE");
BufferedReader bufReader = null;
// open the file for reading
InputStream instream = getResources().openRawResource(rawName);
// if file the available for reading
if (instream != null) {
// prepare the file for reading
InputStreamReader inputreader = new InputStreamReader(instream);
bufReader = new BufferedReader(inputreader);
}
// close the file again
try{instream.close();}
catch (Exception e) {
if(D) Log.e(TAG, "Unable to Close " + filename);}
return bufReader;
}
Each line in the file is supposed to be an entire row in my 2D array. I tried to get a line, tokenize it and put that in the array. But the program keeps crashing. The DDMS Log does does not produce a bunch or errors as I expect
public void getData(){
int rawName = R.raw.values_doubles;
BufferedReader reader_0 = getBufReader(strData2, rawName );
//2D array of x rows and y columns to store the data
//
double[][] Data_temp = new double[size_x][size_y];
String line = null;
StringTokenizer Strtoken;
for(i=0;i<size_x;i++){
try {line = reader_0.readLine();}catch (IOException e) {}
if(line != null){
Strtoken = new StringTokenizer(line);
for(j=0;j<size_y;j++){
if (Strtoken.hasMoreTokens()){
Data_temp[i][j] = Double.parseDouble(Strtoken.nextToken());
CommandsAdapter.add(""+Data_temp[i][j]+" ");
}}
}
CommandsAdapter.add("\n");}}
Please help
Also, I get errors if I don't surroung reader_0.readLine() with try/catch.

I would create a FileInputStream and a Buffered Reader. I am writing this from my lap top so I cannot test this code but this should give you a general idea (my first app saved data on seperate lines in a text file and I could read and write to it using this method)
NOTE this requires you to know how many lines are in your file
FileInputStream fis = new FileInputStream(file);
BufferedReader reader = new BufferedReader(fis);
Double myArray[][] = new Double [Text_File_Lines][6];
StringBuffer buffer = new StringBuffer();
int x = 0;
int y = 0;
while (reader.readLine() != -1) { //indicating end of file
while (reader.nextChar != '\n' ) { //indicating new line
while (reader.nextChar != ' ' ) { //indicating no space character
buffer.append(reader.nextChar());
}
Double[y][x] = Double.parseDouble(buffer.toString()); //Parse double and add it to array
buffer = null; //restore buffer to null
x++;
}
y++;
}
PLEASE NOTE THIS IS VERY SLOPPY CODE THAT ALMOST DEFINITELY WONT WORK this is just to get you started and I will post my working code when I get home from work.

Related

BufferedReader do not read the entire text file

I read about someone having troubles with BufferedReader: the reader simply do not read the first lines. I have instead the opposite problem. For example, in a text file with 300 lines, it arrives at 200, read it half of it and then the following string is given null, so it stops.
private void readerMethod(File fileList) throws IOException {
BigInteger steps = BigInteger.ZERO;
BufferedReader br = new BufferedReader(new FileReader(fileList));
String st;
//reading file line by line
try{
while (true){
st = br.readLine();
if(st == null){
System.out.println("Null string at line " + steps);
break;
}
System.out.println(steps + " - " + st);
steps = steps.add(BigInteger.ONE);
}
}catch(Exception e){
e.printStackTrace();
}
finally{
try{
br.close();
}catch(Exception e){}
}
}
The output of the previous slice of code is as expected until it reaches line 199 (starting from 0). Consider a file with 300 lines.
...
198 - 3B02D5D572B66A82F9D21EE809320DB3E250C6C9
199 - 6E2C69795CB712C27C4097119CE2C5765
Null string at line 200
Notice that, all lines have the same length, so in this output line 199 is not even complete. I checked the file text, and it's correct: it contains all 300 lines and they are all of the same length. Also, in the text there are only capitals letters and numbers, as you can see.
My question is: how can i fix this? I need that the BufferedReader read all the text, not just a part of it.
As someone asked i add here the remaining part of the code. Please notice that all capital names are constant of various type (int, string etc).
This is the method that is called by the main thread:
public void init(){
BufferedWriter bw = null;
List<String> allLines = createRandomStringLines(LINES);
try{
String fileName = "SHA1_encode_text.txt";
File logFile = new File(fileName);
System.out.println(logFile.getCanonicalPath());
bw = new BufferedWriter(new FileWriter(logFile));
for(int i = 0; i < allLines.size(); i++){
//write file
String o = sha1FromString(allLines.get(i));
//sha1FromString is a method that change the aspect of the string,
//replacing char by char. Is not important at the moment.
bw.write(o + "\n");
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
bw.close();
}catch(Exception e){}
}
}
The method that create the list of random string is the following. "SYMBOLS" is just a String contains all avaiable chars.
private List<String> createRandomStringLines(int i) {
List<String> list = new ArrayList<String>();
while(i!=0){
StringBuilder builder = new StringBuilder();
int count = 64;
while (count-- != 0) {
int character = (int)(Math.random()*SYMBOLS.length());
builder.append(SYMBOLS.charAt(character));
}
String generatedString = builder.toString();
list.add(generatedString);
i--;
}
return list;
}
Note that, the file written is totally correct.
Okay, thanks to the user ygor, i manage to resolve it. The problem was that the BufferReader stars his job when the BufferWriter isn't closed yet. It was sufficient to move the command line that require the reader to work, after the bufferWriter.close() command.

Modifying a file at a specific line in Java

I'm writing a method that will allow me to input a line at a specific point in a file, such as a .txt or .vbs script. The problem I'm having is the writing back part, the output file is blank- not containing the entries of my ArrayList scriptCollection. Here is my test method code;
public void testMethod()throws Exception
{
BufferedReader br = new BufferedReader(new FileReader("C:/Users/jchild/Desktop/PrintScript.vbs"));
int indexNo = 1;
int appendAt=0;
String line;
while((line = br.readLine()) != null)
{
scriptCollection.add(line);
if(line.contains("Add at this point"))
{
System.out.println("Successfully read and compared"); //this is just for test output
appendAt = appendAt + indexNo;
}
indexNo++;
}
br.close();
scriptCollection.add(appendAt++,"Appended here");
System.out.println(scriptCollection.toString()); //this is just for test output
//here's what's causing the problem
FileOutputStream fos = new FileOutputStream("C:/Users/jchild/Desktop/PrintScript.txt");
PrintWriter is = new PrintWriter(fos);
for(String temp : scriptCollection)
{
is.println(temp);
}
scriptCollection.clear();
}
You have to close the streams.

how to read from a huge file and write to a new file by java

What I am doing is to read one file line by line, format every line, then write to a new file. But the problem is that the file is huge, nearly 178 MB. But always getting error message: IO console updater error, java heap space. Here is my code:
public class fileFormat {
public static void main(String[] args) throws IOException{
String strLine;
FileInputStream fstream = new FileInputStream("train_final.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(fstream));
BufferedWriter writer = new BufferedWriter(new FileWriter("newOUTPUT.txt"));
while((strLine = reader.readLine()) != null){
List<String> numberBox = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(strLine);
while(st.hasMoreTokens()){
numberBox.add(st.nextToken());
}
for (int i=1; i< numberBox.size(); i++){
String head = numberBox.get(0);
String tail = numberBox.get(i);
String line = head + " "+tail ;
System.out.println(line);
writer.write(line);
writer.newLine();
}
numberBox.clear();
}
reader.close();
writer.close();
}
}
How can I avoid this error message? Moreover, I have set the VM preference: -xms1024m
Remove the line
System.out.println(line);
This is a workaround the fialing console updater, which otherwise runs out of memory.
The program looks okay. I suspect the problem is that you run this inside of Eclipse, and System.out is collected by Eclipse in memory (to be displayed in that Console window).
System.out.println(line);
Try to run it outside of Eclipse, change Eclipse settings to pipe System.out somewhere, or remove the line.
This part of the code:
for (int i=1; i< numberBox.size(); i++){
String head = numberBox.get(0);
String tail = numberBox.get(i);
String line = head + " "+tail ;
System.out.println(line);
writer.write(line);
writer.newLine();
}
Can be translated to:
String head = numberBox.get(0);
for (int i=1; i< numberBox.size(); i++){
String tail = numberBox.get(i);
System.out.print(head);
System.out.print(" ");
System.out.println(tail);
writer.write(head);
writer.write(" ");
writer.write(tail);
writer.newLine();
}
This may add a little code duplication but it avoids creating a lot of objects.
Also there if you merge this for loop with the loop contructing the numberBox, you won't need numberBox structure at all.
If you read whole file the heap memory will occupy so better option in to read the file in chuck. See my below code. It will start reading from the offset given in argument and will return the end offset . You need to pass number of lines to be read.
Please remember: You can use any collection to store these read lines and clear the collection before calling this method to read next chunk.
FileInputStream fis = new FileInputStream(file);
InputStreamReader streamReader = new InputStreamReader(fis, "UTF-8");
LineNumberReader reader = new LineNumberReader(streamReader);
//call this below method recursively until the file does not reaches to the end
public int getParsedLines(LineNumberReader reader, int iLineNumber_Start, int iNumberOfLinesToBeRead) {
int iLineNumber_End = 0;
int iReadUptoLines = iLineNumber_Start + iNumberOfLinesToBeRead;
try {
reader.mark(iLineNumber_Start);
reader.setLineNumber(iLineNumber_Start);
do {
String str = reader.readLine();
if (str == null) {
break;
}
// your code
iLineNumber_End = reader.getLineNumber();
} while (iLineNumber_End != iReadUptoLines);
} catch (Exception ex) {
// exception handling
}
return iLineNumber_End;
}

How to append 4 digit number to the next string read from file

I have one file to read which is like this
mytxt.txt
1234 http://www.abc.com
8754 http://www.xyz.com
I tried with this
try {
// make a 'file' object
File file = new File("e:/mytxt.txt");
// Get data from this file using a file reader.
FileReader fr = new FileReader(file);
// To store the contents read via File Reader
BufferedReader br = new BufferedReader(fr);
// Read br and store a line in 'data', print data
String data;
while((data = br.readLine()) != null)
{
//data = br.readLine( );
System.out.println(data);
}
} catch(IOException e) {
System.out.println("bad !");
}
I used this but the actual question is I want to read one this two charachter one by one and then appens the digit to the link which I'll read as string.
Can anyone tell me how I am suppose to do that..?
any help would be appreciated.
Parse the line you are reading, search for the first white space (I'm assuming you have only one space separating your digit and your url) something like this:
try {
// make a 'file' object
File file = new File("e:/mytxt.txt");
// Get data from this file using a file reader.
FileReader fr = new FileReader(file);
// To store the contents read via File Reader
BufferedReader br = new BufferedReader(fr);
// Read br and store a line in 'data', print data
String data;
while((data = br.readLine()) != null)
{
int posWhite = data.indexOf(' ');
String digit = data.substring(0, posWhite);
String url = data.substring(posWhite + 1);
System.out.println(url + "/" + digit);
}
} catch(IOException e) {
System.out.println("bad !");
}
Is this what you want?
while((data = br.readLine()) != null)
{
String[] data=br.readLine().split();
if(data!=null&&data.length==2)
{
System.out.println(data[1]+"/"+data[0]);
}else
{
System.out.println("bad string!");
}
}
In the while((data = br.readLine()) != null), make the code like this:
String tmpData[] = data.split(" ");
System.out.println(tmpData[1] + "/" + tmpData[0]);

How to Access string in file by position in Java

I have a text file with the following contents:
one
two
three
four
I want to access the string "three" by its position in the text file in Java.I found the substring concept on google but unable to use it.
so far I am able to read the file contents:
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
I want to apply the substring concept to the file.It asks for the position and displays the string.
String Str = new String("Welcome to Tutorialspoint.com");
System.out.println(Str.substring(10, 15) );
If you know the byte offsets within the file that you are interested in then it's straightforward:
RandomAccessFile raFile = new RandomAccessFile("textfile.txt", "r");
raFile.seek(startOffset);
byte[] bytes = new byte[length];
raFile.readFully(bytes);
raFile.close();
String str = new String(bytes, "Windows-1252"); // or whatever encoding
But for this to work you have to use byte offsets, not character offsets - if the file is encoded in a variable-width encoding such as UTF-8 then there's no way to seek directly to the nth character, you have to start at the top of the file and read and discard the first n-1 characters.
look for \r\n (linebreaks) in your text file. This way you should be able to count the rows containing your string.
your file in reality looks like this
one\r\n
two\r\n
three\r\n
four\r\n
You seem to be looking for this. The code I posted there works on the byte level, so it may not work for you. Another option is to use the BufferedReader and just read a single character in a loop like this:
String getString(String fileName, int start, int end) throws IOException {
int len = end - start;
if (len <= 0) {
throw new IllegalArgumentException("Length of string to output is zero or negative.");
}
char[] buffer = new char[len];
BufferedReader reader = new BufferedReader(new FileReader(fileName));
for (int i = 0; i < start; i++) {
reader.read(); // Ignore the result
}
reader.read(buffer, 0, len);
return new String(buffer);
}

Categories

Resources