Best way to read data from a file [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Best way to read a text file
In Java I can open a text file like this:
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
My question is, how do you read from the following file? The first line is a number (830) representing number of words, and the following lines contain the words.
830
cooking
English
weather
.
.
I want to read the words into a string array. But how do I read the data first?

You're on the right track; I would treat the first line as a special case by parsing it as an integer (see Integer#parseInt(String)) then reading the words as individual lines:
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
String numLinesStr = reader.readLine();
if (numLinesStr == null) throw new Exception("invalid file format");
List<String> lines = new ArrayList<String>();
int numLines = Integer.parseInt(numLinesStr);
for (int i=0; i<numLines; i++) {
lines.add(reader.readLine());
}

Unless you have some special reason, it's not necessary to keep track of how many lines the file contain. Just use something like this:
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
String line;
while ((line = reader.readLine()) != null) {
// ...
}

If you're working with Java version greater than 1.5, you can also use the Scanner class:
Scanner sc = new Scanner(new File("someTextFile.txt"));
List<String> words = new ArrayList<String>();
int lines = sc.nextInt();
for(int i = 1; i <= lines; i++) {
words.add(sc.nextLine());
}
String[] w = words.toArray(new String[]{});

Try the class java.io.BufferedReader, created on a java.io.FileReader.
This object has the method readLine, which will read the next line from the file:
try
{
java.io.BufferedReader in =
new java.io.BufferedReader(new java.io.FileReader("filename.txt"));
String str;
while((str = in.readLine()) != null)
{
...
}
}
catch(java.io.IOException ex)
{
}

You could use reflection and do this dynamically:
public static void read() {
try {
BufferedReader reader = new BufferedReader(new FileReader(
"filename.txt"));
String line = reader.readLine();
while (line != null) {
if (Integer.class.isAssignableFrom(line.getClass())) {
int number = Integer.parseInt(line);
System.out.println(number);
} else {
String word = line;
System.out.println(word);
}
line = reader.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Related

Read from csv file with split missing in Java

I want to read csv file with BufferedReader and split with StringTokenizer. However there is one line in file which contains this line :
ide,12,office,,3208.83,0.18,577.5,4876
Also here is my read method;
public void readFromCSV(){
try {
File file = new File(myFile);
br = new BufferedReader(new FileReader(file));
String line = null;
while((line = br.readLine()) != null) {
st1 = new StringTokenizer(line,"\n");
while(st1.hasMoreTokens()) {
oneLineList = new ArrayList<>();
st2 = new StringTokenizer(st1.nextToken(),",");
for(int i = 0; i < 8; i++) {
oneLineList.add(st2.nextToken());
}
dataList.add(counter,oneLineList);
}
counter++;
}
br.close();
}catch(IOException ex) {
ex.printStackTrace();
}
}
In for statement, there are 8 fields in each line, and dataList is a two-dimensional array list.
I cannot read whole data because of one line contain consecutive coma, how should I do for fix this?

print Float value as it is

I have read a content from a file which is in my local system.It is in float type.So while printing the output I could not get value before the decimal point.What needs to be included so that i will get an exact output.
I want the output like 1.68765 But I am getting .68765
Also i need to append output from another file with this out.
Content of the file will be like this but without double line spaces inbetween.Next to each other but in next next line
1
.
6
8
7
6
5
Here is my code
package testing;
import java.io.*;
class read {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("D:/Movies/test.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
line = br.readLine();
System.out.println(line);
}
} finally {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
As you may see, you're skipping the first line by using the following. You're reading two lines before printing one so the first is skipped.
String line = br.readLine();
while (line != null) {
line = br.readLine();
System.out.println(line);
}
Solution
StringBuilder sb = new StringBuilder();
String line;
while ((line=br.readLine()) != null) {
sb.append(line);
}
float myFloat = Float.valueOf(sb.toString());
Assign the value of the line from the file directly in your loop test. This will save you from headaches and is way more intuitive.
Now since you already have a StringBuilder object, I suggest you append all the lines and then cast its value to a float.
String line = br.readLine(); had read the first line ,use
String line = "";
I suggest using the scanner class to read your input and the nextFloat class to get the next floating point number -
Scanner scanner = new Scanner(new File("D:/Movies/test.txt"));
while(scanner.hasNextFloat()) {
System.out.println(scanner.nextFloat());
}
Basicay you are skipping first line as #yassin-hajaj mentioned, you can solve this in 2 ways:
In JDK8 it would look like this:
Stream<String> lines = Files.lines(Paths.get("D:/Movies/test.txt"));
String valueAsString = lines.collect(Collectors.joining()); // join all characters into a string
Float value = Float.valueOf(valueAsString);// parse it to a float
System.out.printf("%.10f", value); // will print vlaue with 10 digits after comma
Or you can do it by (JDK7+):
StringBuilder sb = new StringBuilder();
try ( BufferedReader br = new BufferedReader(new FileReader("D:/Movies/test.txt"))){ // this will close are streams after exiting this block
String line;
while ((line = br.readLine())!=null) { // read line and assign to line variable
System.out.println(line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("F:/test.txt"));
try {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} finally {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
You can also put the readLine() method within the while condition.
Also, float may not be printed the way you expect, ie, fewer digits will be displayed.
public class Reader {
public static void main(String[] args) throws IOException, NumberFormatException {
BufferedReader br = new BufferedReader(new FileReader("D:/test.txt"));
String line = null;
while ((line = br.readLine()) != null)
System.out.println(Double.parseDouble(line));
br.close();
}
}
Sample output:
1.68765
54.4668489
672.9821368

Read text file line by line and store in a class?

I need some help with reading line by line from a file then put it into a class.
My idea is like this: I've saved everything in a text file, it's about 500 lines but this can change that's why I wan't the line number reader and then lnr/5 to get how many times I'll need to run the for loop. I wan't it to first take line 1,2,3,4,5 into a object, then 6,7,8,9,10 and so on. So basically I need each 5 lines go in seperatley.
Code:
public static void g_txt() {
LineNumberReader lnr;
String[] text_array = new String[500];
int nu = 0;
try {
lnr = new LineNumberReader(new FileReader(new File("test.txt")));
lnr.skip(Long.MAX_VALUE);
//System.out.println(lnr.getLineNumber());
lnr.close();
BufferedReader br = new BufferedReader(new FileReader("test.txt"));
String line;
while ((line = br.readLine()) != null) {
text_array[nu] = line;
nu++;
}
} catch (IOException e) {
}
}
as you can see, I now has it in an array. Now I need it to make so 1,2,3,4,5 and so on go in to this:
filmer[antalfilmer] = new FilmSvDe(line1);
filmer[antalfilmer].s_filmbolag(line2);
filmer[antalfilmer].s_producent(line3);
filmer[antalfilmer].s_tid(line4);
filmer[antalfilmer].s_betyg(line5);
filmer[antalfilmer].s_titel(line1);
then antalfilmer++.
public static void g_txt() {
String[] text_array = new String[5];
int nu = 0;
try {
BufferedReader br = new BufferedReader(new FileReader("test.txt"));
String line;
while ((line = br.readLine()) != null) {
text_array[nu] = line;
nu++;
if (nu == 5) {
nu = 0;
makeObject(text_array);
}
}
} catch (IOException e) {
}
}
private static void makeObject(String[] text_array) {
// do your object creation here
System.out.println("_________________________________________________");
for (String string : text_array) {
System.out.println(string);
}
System.out.println("_________________________________________________");
}
Try this.

skip inserting first line of csv file

I have a method that takes data from a .csv file and puts it into an array backwards
(first row goes in last array slot) however I would like the first row in the .csv file to not be in the array. How would I accomplish this? Here is my code thus far:
public static String[][] parse(String symbol) throws Exception{
String destination = "C:/"+symbol+"_table.csv";
LineNumberReader lnr = new LineNumberReader(new FileReader(new File(destination)));
lnr.skip(Long.MAX_VALUE);
String[][] stock_array = new String[lnr.getLineNumber()][3];
try{
BufferedReader br = new BufferedReader(new FileReader(destination));
String strLine = "";
StringTokenizer st = null;
int line = lnr.getLineNumber()-1;
while((strLine = br.readLine()) != null){
st = new StringTokenizer(strLine, ",");
while(st.hasMoreTokens()){
stock_array[line][0] = st.nextToken();
st.nextToken();
stock_array[line][1] = st.nextToken();
stock_array[line][2] = st.nextToken();
st.nextToken();
st.nextToken();
st.nextToken();
}
line--;
}
}
catch(Exception e){
System.out.println("Error while reading csv file: " + e);
}
return stock_array;
}
You can skip the first line by just reading it in and doing nothing. Do this just before your while loop:
br.readLine();
To make sure that your array is the right size and lines get stored in the right places, you should also make these changes:
String[][] stock_array = new String[lnr.getLineNumber()-1][3];
...
int line = lnr.getLineNumber()-2;
Your code is not efficient, as far as my knowledge goes. Also, you are using linenumberreader.skip(long.max_value), which is not a correct/confirmed way to find the line count of the file. StringTokenizer is kind of deprecated way of splitting tokens. I would code it, in the following way:
public static List<String[]> parse(String symbol) throws Exception {
String destination = "C:/"+symbol+"_table.csv";
List<String[]> lines = new ArrayList<String[]>();
try{
BufferedReader br = new BufferedReader(new FileReader(destination));
int index = 0;
while((line = br.readLine()) != null){
if(index == 0) {
index++;
continue; //skip first line
}
lines.add(line.split(","));
}
if(lines != null && !lines.isEmpty()) {
Collections.reverse(lines);
}
} catch(IOException ioe){
//IOException Handling
} catch(Exception e){
//Exception Handling
}
return lines;
}

How can I read input from a file line by line in java? [duplicate]

This question already has answers here:
How can I read a large text file line by line using Java?
(22 answers)
Closed 6 years ago.
Ok, I know this is a really rookie question, but I looked around online a lot and am yet unable to find the answer to my question:
How can I read input from a file line by line in java?
Assume a file input that has integers on each line, like:
1
2
3
4
5
Here's the snippet of code I am trying to work with:
public static void main(File fromFile) {
BufferedReader reader = new BufferedReader(new FileReader(fromFile));
int x, y;
//initialize
x = Integer.parseInt(reader.readLine().trim());
y = Integer.parseInt(reader.readLine().trim());
}
Presumably, this would read in the first two lines and store them as integers in x and y. So going off the example, x=1, y=2.
It is finding a problem with this, and I don't know why.
public static void main(String[] args) {
FileInputStream fstream;
DataInputStream in = null;
try {
// Open the file that is the first
// command line parameter
fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
int x = Integer.parseInt(br.readLine());
int y = Integer.parseInt(br.readLine());
//Close the input stream
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
} finally {
try {
in.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
please check your main method(). It should be like these
public static void main(String... args) {
}
or
public static void main(String[] args) {
}
then read like that :
BufferedReader reader = new BufferedReader(new FileReader(fromFile));
String line;
while( (line = reader.readLine()) != null){
int i = Integer.parseInt(line);
}
We usually use a while loop, the readLine method tells whether the end of file is reached or not:
List<String> lines = new ArrayList<String>();
while ((String line = reader.readLine()) != null)
lines.add(line);
Now we have a collection (a list) that holds all lines from the file as separate strings.
To read the content as Integers, just define a collection of integers and parse while reading:
List<Integer> lines = new ArrayList<Integer>();
while ((String line = reader.readLine()) != null) {
try {
lines.add(Integer.parseInt(line.trim()));
} catch (NumberFormatException eaten) {
// this happens if the content is not parseable (empty line, text, ..)
// we simply ignore those lines
}
}

Categories

Resources