-1

I have text file which i have read once user upload, how can i read using java code, can any one give some suggestion which would very helpful to me

sample file looks like below

SNR   Name
1     AAR
2     BAT
3     VWE
Pshemo
  • 113,402
  • 22
  • 170
  • 242
  • There are many ways to read this file. You can read it line-by-line and handle tokens from each line separately, or word-by-word assuming each line will have same amount of words. All this can be achieved with Scanner class. Take a look at its documentation to get more detailed info. – Pshemo Apr 28 '17 at 10:40

3 Answers3

0

A common pattern is to use

try (BufferedReader br = new BufferedReader(new FileReader(file)) ) {
String line;
while ((line = br.readLine()) != null) {
    // process the line to insert in database.
}}
0

The easiest way is use Scanner() object

Scanner sc = new Scanner(new File("myFile.txt"));

use

boolean hasNext = sc.hasNext();

to know if there are more items in the file

and

String item = sc.next();

to get items secuentially.

I attach the documentation (it provides very good code examples) https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

David Marciel
  • 767
  • 1
  • 11
  • 25
0

You can use BufferedReader to read file line by line. So, even if your file is too big, then also it will read line by line only. It won't load entire file. Declaration will be similar to this.

BufferedReader br = new BufferedReader(new FileReader(FILENAME)); And you can use command

while ((sCurrentLine = br.readLine()) != null) { .....// process }

to read file till end. Obviously, you have to use seperator in file to split the records in each line. And store accordingly in java objects. After that you can store in DB through DAO.

user3462649
  • 929
  • 2
  • 8
  • 16