Read txt file and convert to array - java

I don't understand why this code won't read a .txt file then convert it to an array. I don't have the exact number of rows to begin with (to set the array) so I count the .txt files rows with a while loop.
This program should count the number of rows it imports then create a new array to copy & print the information to the console.
public class Cre{
public void openFile() throws IOException{
BufferedReader in = new BufferedReader(new FileReader("C:\\Users\\file.txt"));
String line = in.readLine();
int i=0;
String linecounterguy = "null";
int count = 0;
while(line!= null) { ///to count number of rows///
linecounterguy = in.readLine();
count += 1;
}
String[] array = new String[count+1];
String line1 = "try";
while(line!= null)
{
line1 = in.readLine();
System.out.println(line1);
}
in.close();
for (int j = 0; j < array.length-1 ; j++) {
linecounterguy = in.readLine();
System.out.println(array[j]);
}
}
}
Main Class
> public class JavaApplication8 {
>
> /**
> * #param args the command line arguments
> */
> public static void main(String[] args) throws IOException {
>
>
> Cre k = new Cre();
> k.openFile();
>
>
> } }

Here is a little method that will get you started with reading a text file into an array of strings. Hope this helps!
public String[] readLines(String filename) throws IOException {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
bufferedReader.close();
return lines.toArray(new String[lines.size()]);
}

Related

Read a particular data corresponding to a row & column in CSV

I need some help. I want to implement a code where-in I wish to read data from a csv file.
Sample CSV file (details.csv) :
id,name,age
1,bh,23
2,nit,24
I want to create such a method in java to read this CSV that I pass the sheetname, columnname and rowname as parameters. Where ever there is a match of this combination, the corresponding data is picked.
Example :- I want to pass details.csv,name & 1. I should get the output as bh.
Could you please help me with this?
I tried with the following code but it is returning null value :-
public static String searchCsvLine(String filename, String searchString, String rowname) throws IOException {
String resultRow = null;
BufferedReader br = new BufferedReader(new FileReader(filename));
String line;
while ( (line = br.readLine()) != null ) {
String[] values = line.split(",");
if(values.equals(searchString)) {
resultRow = line;
break;
}
}
br.close();
return resultRow;
}
You should parse the first line of csv file to get column names.
public class Test {
public static String searchCsvLine(String filename, String columnName, String rowName) throws IOException {
String resultRow = null;
BufferedReader br = new BufferedReader(new FileReader(filename));
// parse first line as column names
String line = br.readLine();
String[] columns = line.split(",");
int columnIndex = -1;
for (int i = 0; i < columns.length; i++) {
if (columnName.equals(columns[i])) {
columnIndex = i;
break;
}
}
// read lines to match row
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
if (rowName.equals(values[0])) {
// return value at columnIndex
resultRow = values[columnIndex];
break;
}
}
br.close();
return resultRow;
}
public static void main(String[] args) throws IOException {
String name = searchCsvLine("details.cvs", "name", "1");
System.out.println("name is " + name);
}
}
Try below :
public static String searchCsvLine(String filename, String searchString,String rowname) throws IOException {
String resultRow = null;
BufferedReader br = new BufferedReader(new FileReader(filename));
String line;
int searchStringIndex=0;
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
//get index of searchString
for (int i = 0; i < values.length; i++) {
if(values[i].equalsIgnoreCase(searchString)){
searchStringIndex=i;
break;
}
}
//get required rowname
for (int i = 0; i < Integer.parseInt(rowname); i++) {
line=br.readLine();
}
//split the line found by rowname and get value as per searchString index (given column)
values = line.split(",");
resultRow=values[searchStringIndex];
break;
}
br.close();
System.out.println(resultRow);
return resultRow;
}
}

How do I put text file into a hash table in Java?

I have a text file, I want to read it and place it into my hash table.
Then print it.
I have written a block of code, what am I doing wrong?
public static void main(String[] args) throws FileNotFoundException, IOException {
Hashtable< Integer, String > hash = new Hashtable< Integer, String >();
BufferedReader rd = new BufferedReader( new FileReader ("students.txt"));
String line = "";
int i = 0;
while (line != null){
line = rd.readLine();
hash.put(i, line);
i++;
}
for ( int j = 0 ; j < hash.size() ; j++){
System.out.println(hash.get(j));
}
}
Code looks good . Correcting one bug below
BufferedReader br = new BufferedReader(new FileReader ("students.txt"));
while ((thisLine = br.readLine()) != null) {
System.out.println(thisLine);
}
I am using your code and I have corrected some bugs...
I think, this code is not right but he works :)
try{
Hashtable< Integer, String > hash = new Hashtable< Integer, String >();
BufferedReader rd = new BufferedReader( new FileReader ("students.txt"));
String line;
int i = 0;
while ((line = rd.readLine()) != null){
hash.put(i, line);
i++;
}
for ( int j = 0 ; j < hash.size() ; j++){
System.out.println(hash.get(j));
}
}catch(FileNotFoundException e){}catch (IOException e) {}

converting a string array to a double array

I am trying to convert a list of numbers from a txt file into an array of numbers. There is 26 numbers, and each is on a different line in the text file. My code is
import java.io.*;
public class rocket {
public static void main(String[] args) throws IOException, FileNotFoundException
{
BufferedReader b = new BufferedReader(new InputStreamReader(new FileInputStream("/Users/Jeremy/Documents/workspace/altitude.txt")));
String[] stringArray = new String[25];
double[] doubleArray = new double[stringArray.length];
for(int i=0; i<25; i++)
{
stringArray[i] = b.readLine();
doubleArray[i] = Double.parseDouble(stringArray[i]);
}
for(int i = 0; i<doubleArray.length; i++)
{
System.out.println(doubleArray[i]);
}
}
}
But every time I run it I get a number format exception. And if I try to just print out the strings I get an indexOutOfBounds exception
in question you have mentioned that there is 26 strings so declate
String[] stringArray = new String[26];
And The number format exception is occuring as readline returns with the linbreak. To read line you can do the following
public String[] readLines(String filename) throws IOException {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
bufferedReader.close();
return lines.toArray(new String[lines.size()]);
}
So by this logic you can get double by
public static Double[] readLines(String filename) throws IOException {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<Double> lines = new ArrayList<Double>();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(Double.parseDouble(line));
}
bufferedReader.close();
return lines.toArray(new Double[lines.size()]);
}
Try
BufferedReader b = new BufferedReader(
new InputStreamReader(
new FileInputStream(
"D:/git-repo/general/misc_test/src/java/com/greytip/cougar/module/test/v2/controller/so/dump/data.txt")));
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = b.readLine()) != null) {
lines.add(line);
}
String[] stringArray = lines.toArray(new String[lines.size()]);
double[] doubleArray = new double[stringArray.length];
for (int i = 0; i < stringArray.length; i++) {
doubleArray[i] = Double.parseDouble(stringArray[i]);
}
for (int i = 0; i < doubleArray.length; i++) {
System.out.println(doubleArray[i]);
}
String[] stringArray = new String[26];
try this
import java.io.*;
public class Rocket {
public static void main(String[] args) throws IOException, FileNotFoundException
{
BufferedReader b = new BufferedReader(new InputStreamReader(new FileInputStream("/Users/Jeremy/Documents/workspace/altitude.txt")));
String[] stringArray = new String[25];
double[] doubleArray = new double[stringArray.length];
for(int i=0; i<25; i++)
{
stringArray[i] = b.readLine();
try{
doubleArray[i] = Double.parseDouble(stringArray[i]);
}catch(Exception e)
{
e.printStackTrace();
}
}
for(int i = 0; i<doubleArray.length; i++)
{
System.out.println(doubleArray[i]);
}
}
}
Handle the Exception when parse a string to double please.

Reading text from file and storing each word from every line into separate variables

I have a .txt file with the following content:
1 1111 47
2 2222 92
3 3333 81
I would like to read line-by-line and store each word into different variables.
For example: When I read the first line "1 1111 47", I would like store the first word "1" into var_1, "1111" into var_2, and "47" into var_3. Then, when it goes to the next line, the values should be stored into the same var_1, var_2 and var_3 variables respectively.
My initial approach is as follows:
import java.io.*;
class ReadFromFile
{
public static void main(String[] args) throws IOException
{
int i;
FileInputStream fin;
try
{
fin = new FileInputStream(args[0]);
}
catch(FileNotFoundException fex)
{
System.out.println("File not found");
return;
}
do
{
i = fin.read();
if(i != -1)
System.out.print((char) i);
} while(i != -1);
fin.close();
}
}
Kindly give me your suggestions. Thank You
public static void main(String[] args) throws IOException {
File file = new File("/path/to/InputFile");
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line = null;
while( (line = br.readLine())!= null ){
// \\s+ means any number of whitespaces between tokens
String [] tokens = line.split("\\s+");
String var_1 = tokens[0];
String var_2 = tokens[1];
String var_3 = tokens[2];
}
}
try {
BufferedReader fr = new BufferedReader(new InputStreamReader(new FileInputStream(file), "ASCII"));
while(true)
{
String line = fr.readLine();
if(line==null)
break;
String[] words = line.split(" ");//those are your words
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
Hope this Helps!
Check out BufferedReader for reading lines. You'll have to explode the line afterwards using something like StringTokenizer or String's split.
import java.io.*;
import java.util.Scanner;
class Example {
public static void main(String[] args) throws Exception {
File f = new File("main.txt");
StringBuffer txt = new StringBuffer();
FileOutputStream fos = new FileOutputStream(f);
for (int i = 0; i < args.length; i++) {
txt.append(args[i] + " ");
}
fos.write(txt.toString().getBytes());
fos.close();
FileInputStream fis = new FileInputStream("main.txt");
InputStreamReader input = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(input);
String data;
String result = new String();
StringBuffer txt1 = new StringBuffer();
StringBuffer txt2 = new StringBuffer();
File f1 = new File("even.txt");
FileOutputStream fos1 = new FileOutputStream(f1);
File f2 = new File("odd.txt");
FileOutputStream fos2 = new FileOutputStream(f2);
while ((data = br.readLine()) != null) {
result = result.concat(data);
String[] words = data.split(" ");
for (int j = 0; j < words.length; j++) {
if (j % 2 == 0) {
System.out.println(words[j]);
txt1.append(words[j] + " ");
} else {
System.out.println(words[j]);
txt2.append(words[j] + " ");
}
}
}
fos1.write(txt1.toString().getBytes());
fos1.close();
fos2.write(txt2.toString().getBytes());
fos2.close();
br.close();
}
}

The first element discarded while sorting text file using arrays in java

I have this code to sort a text file using arrays in java, but it always discard the first line of the text while sorting.
Here is my code:
import java.io.*;
public class Main {
public static int count(String filename) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try {
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
while ((readChars = is.read(c)) != -1) {
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++count;
}
}
}
return count;
} finally {
is.close();
}
}
public static String[] getContents(File aFile) throws IOException {
String[] words = new String[count(aFile.getName()) + 1];
BufferedReader input = new BufferedReader(new FileReader(aFile));
String line = null; //not declared within while loop
int i = 0;
while ((line = input.readLine()) != null) {
words[i] = line;
i++;
}
java.util.Arrays.sort(words);
for (int k = 0; k < words.length; k++) {
System.out.println(words[k]);
}
return words;
}
public static void main(String[] args) throws IOException {
File testFile = new File("try.txt");
getContents(testFile);
}
}
Here is the text file try.txt:
Daisy
Jane
Amanda
Barbara
Alexandra
Ezabile
the output is:
Alexandra
Amanda
Barbara
Ezabile
Jane
Daisy
To solve this problem I have to insert an empty line in the beginning of the text file, is there a way not to do that? I don't know what goes wrong?
I compiled your code (on a Mac) and it works for me. Try opening the file in a hexeditor and see if there is some special character at the beginning of your file. That might be causing the sorting to be incorrect for the first line.
You probably have a BOM (Byte Order Marker) at the beginning at the file. By definition they will be interpreted as zero-width non-breaking-space.
So if you have
String textA = new String(new byte[] { (byte)0xef, (byte)0xbb, (byte) 0xbf, 65}, "UTF-8");
String textB = new String(new byte[] { 66}, "UTF-8");
System.err.println(textA + " < " + textB + " = " + (textA.compareTo(textB) < 0));
The character should show up in your length of the strings, so try printing the length of each line.
System.out.println(words[k] + " " + words[k].length());
And use a list or some other structure so you don't have to read the file twice.
Try something simpler, like this:
public static String[] getContents(File aFile) throws IOException {
List<String> words = new ArrayList<String>();
BufferedReader input = new BufferedReader(new FileReader(aFile));
String line;
while ((line = input.readLine()) != null)
words.add(line);
Collections.sort(words);
return words.toArray(new String[words.size()]);
}
public static void main(String[] args) throws IOException {
File testFile = new File("try.txt");
String[] contents = getContents(testFile);
for (int k = 0; k < contents.length; k++) {
System.out.println(contents[k]);
}
}
Notice that you don't have to iterate over the file to determine how many lines it has, instead I'm adding the lines to an ArrayList, and at the end, converting it to an array.
Use List and the add() method to read your file contents.
Then use Collections.sort() to sort the List.

Categories

Resources