> Reading from file in java ?

Reading from file in java ?

Posted at: 2014-12-18 
import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.Scanner;

public class Program {

public static void main(String[] args) {

File fileIn = new File("C:\\Users\\LENOVO\\Desktop\\cool.t...

File fileOut = new File("C:\\Users\\LENOVO\\Desktop\\JACK.t...

Service service = new Service();

try {

Student student = service.read(fileIn);

service.save(fileOut, student);

} catch (Exception ex) {

ex.printStackTrace();

}

}

}

class Service {

public Student read(File source) throws FileNotFoundException {

Student student = null;

Scanner file = new Scanner( source);

if (file.hasNext()) {

String line = file.nextLine();

String action = line.split("\\s")[0];

if ("ADDSTUDENT".equalsIgnoreCase( action)) {

int pos = line.indexOf(' ');

student = new Student( line.substring(pos + 1));

}

}

file.close();

return student;

}

public void save(File file, Student student) throws IOException {

if (!file.exists()) {

file.createNewFile();

}

FileOutputStream fos = new FileOutputStream( file);

byte[] data = student.toString( ).getBytes();

fos.write(data);

fos.flush();

fos.close();

}

}

class Student {

private int id;

private String firstName;

private String lastName;

public Student() {

}

public Student(String value) {

String[] fields = value.split("\\s");

id = Integer.parseInt(fields[0]);

firstName = fields[1];

lastName = fields[2];

}

@Override

public String toString() {

return String.format("Id:%d FirstName:%s LastName:%s", id, firstName,

lastName);

}

}

You could use buffered reader to read the whole line as string then split the string using space as delimiter. That should give you array of strings, str[0] will be ADDSTUDENT, str[1] will be id etc..

Same in scanner can be achieved in scanner using useDelimiter(String pattern) method

set in.useDelimiter(patternYouNeed)

pattern you need will be newline (\n) or return carriage (\r) pick which suits your needs.

Hi,

now suppose i have a file called >cool.txt< and it contains :

" ADDSTUDENT 12345 JOHN WILLIAMS "

MY CODE GOES LIKE THIS :

File inf = new File ("C:\\Users\\LENOVO\\Desktop\\cool.txt");

File outf = new File ("C:\\Users\\LENOVO\\Desktop\\JACK.txt");

Scanner in = new Scanner(inf);

PrintWriter out = new PrintWriter(outf);

;

String s = "";



String firstName ;

String lastName ;

int ID;



while(in.hasNext()){

s = in.next();

if(s.equals("ADDSTUDENT")){

/*her i want to read the id number, first name and last name and save them to ID, firstName and lastName

respectively*/

}}