How to add Zero before the name depending on name lenght - java

i am doing a sample program where i need to get the values from database as example candidatename and to write a .txt file and this part is ok for me. my problem is in .txt file the name value is fixed length so i need to add some 0 before the name to fulfil that condition . for example my name lenght in .txt file is 10 char and if my name is "amar" then i need to add some 0 before the name as "0000000amar". i am attaching my code bellow
package com.myapp.struts.Action;
public class Main {
public static final long RECORD_LENGTH = 100;
public static final String EMPTY_STRING = " ";
public static final String CRLF = "\n";
public static void main(String[] argv) throws Exception {
String a="";
String q="";
PrintWriter writer=null;
try
{
File file=new File("c:/report");
file.mkdirs();
Connection connection = mbjBaseDAO.getConnection();
Statement stmt = connection.createStatement();
String query="select candidate_name from online_application ";
ResultSet rs=stmt.executeQuery(query);
while(rs.next())
{
a=rs.getString("candidate_name");
int lenght=a.length();
System.out.println("lenght is"+lenght);
System.out.println(q);
writer=new PrintWriter("c:/report/challan.txt");
for(int i=0;i<10;i++)
{
writer.print(q+"\t");
if((i)==i)
{
writer.println();
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
writer.flush();
writer.close();
}
}
public static String paddingRight(String source)
{
StringBuilder result = new StringBuilder(100);
if(source != null)
{
result.append(source);
for (int i = 0; i < RECORD_LENGTH - source.length(); i++)
{
result.append(EMPTY_STRING);
}
}
return result.toString();
}
}
Please help

String str = "amar";
str = String.format("%11s", str).replace(' ', '0');
System.out.println(str); // 0000000amar

Related

Specified text file not found for File I/O in Eclipse

I am trying to do a file I/O in eclipse. Here is the code:
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;
public class TextDB {
public static final String SEPARATOR = "|";
// an example of reading
public static ArrayList readProfessors(String filename) throws IOException {
// read String from text file
ArrayList stringArray = (ArrayList) read(filename);
ArrayList alr = new ArrayList();// to store Professors data
for (int i = 0; i < stringArray.size(); i++) {
String st = (String) stringArray.get(i);
// get individual 'fields' of the string separated by SEPARATOR
StringTokenizer star = new StringTokenizer(st, SEPARATOR); // pass in the string to the string tokenizer using delimiter ","
String name = star.nextToken().trim(); // first token
String email = star.nextToken().trim(); // second token
int contact = Integer.parseInt(star.nextToken().trim()); // third token
// create Professor object from file data
Professor prof = new Professor(name, email, contact);
// add to Professors list
alr.add(prof);
}
return alr;
}
// an example of saving
public static void saveProfessors(String filename, List al) throws IOException {
List alw = new ArrayList();// to store Professors data
for (int i = 0; i < al.size(); i++) {
Professor prof = (Professor) al.get(i);
StringBuilder st = new StringBuilder();
st.append(prof.getName().trim());
st.append(SEPARATOR);
st.append(prof.getEmail().trim());
st.append(SEPARATOR);
st.append(prof.getContact());
alw.add(st.toString());
}
write(filename, alw);
}
/**
* Write fixed content to the given file.
*/
public static void write(String fileName, List data) throws IOException {
PrintWriter out = new PrintWriter(new FileWriter(fileName));
try {
for (int i = 0; i < data.size(); i++) {
out.println((String) data.get(i));
}
} finally {
out.close();
}
}
/**
* Read the contents of the given file.
*/
public static List read(String fileName) throws IOException {
List data = new ArrayList();
Scanner scanner = new Scanner(new FileInputStream(fileName));
try {
while (scanner.hasNextLine()) {
data.add(scanner.nextLine());
}
} finally {
scanner.close();
}
return data;
}
public static void main(String[] aArgs) {
TextDB txtDB = new TextDB();
String filename = "professor.txt";
try {
// read file containing Professor records.
ArrayList al = TextDB.readProfessors(filename);
for (int i = 0; i < al.size(); i++) {
Professor prof = (Professor) al.get(i);
System.out.println("Name " + prof.getName());
System.out.println("Contact " + prof.getContact());
}
Professor p1 = new Professor("Joseph", "jos#ntu.edu.sg", 67909999);
// al is an array list containing Professor objs
al.add(p1);
// write Professor record/s to file.
TextDB.saveProfessors(filename, al);
} catch (IOException e) {
System.out.println("IOException > " + e.getMessage());
}
}
}
And my Professor class:
import java.io.Serializable;
public class Professor implements Serializable {
private String name;
private String email;
private int contact;
public Professor(String n, String e, int c) {
name = n;
email = e;
contact = c;
}
public String getName() {
return name;
}
public int getContact() {
return contact;
}
public String getEmail() {
return email;
}
public boolean equals(Object o) {
if (o instanceof Professor) {
Professor p = (Professor) o;
return (getName().equals(p.getName()));
}
return false;
}
}
However, when I run it, the compiler told the the specified file "professor.txt" is not found. I thought the compiler will create the text file automatically based on these code?
Thanks in advance.
Before attempting to read the file in your application, create it if it doesn't exist, either directly :
String filename = "professor.txt" ;
File file = new File(fileName);
if(!file.exists()){
file.createNewFile();
}
Or by calling your write method.
String filename = "professor.txt" ;
File file = new File(fileName);
if(!file.exists()){
TextDB.saveProfessors(filename, new ArrayList());
}
The PrintWriter will create the file for you, even though nothing is written to it (like with this empty list).
In your main you are firstly reading the file and then write it: if the file doesn't exist it will throw you the exception. Probably, the first time you ran it, the file was present (maybe you have write the code to write the file first and then you have launch it).
so, two solutions...
First: change the order of your main.
public static void main(String[] aArgs) {
TextDB txtDB = new TextDB();
String filename = "professor.txt";
try {
Professor p1 = new Professor("Joseph", "jos#ntu.edu.sg", 67909999);
// al is an array list containing Professor objs
al.add(p1);
// write Professor record/s to file.
TextDB.saveProfessors(filename, al);
// read file containing Professor records.
ArrayList al = TextDB.readProfessors(filename);
for (int i = 0; i < al.size(); i++) {
Professor prof = (Professor) al.get(i);
System.out.println("Name " + prof.getName());
System.out.println("Contact " + prof.getContact());
}
} catch (IOException e) {
System.out.println("IOException > " + e.getMessage());
}
}
Second: check if the file exist or not and then skip the read of it if it doesn't
public static void main(String[] aArgs) {
TextDB txtDB = new TextDB();
String filename = "professor.txt";
try {
//check if the file exist
File oFile = new File(filename);
if(oFile.exist()) {
// read file containing Professor records.
ArrayList al = TextDB.readProfessors(filename);
for (int i = 0; i < al.size(); i++) {
Professor prof = (Professor) al.get(i);
System.out.println("Name " + prof.getName());
System.out.println("Contact " + prof.getContact());
}
}
Professor p1 = new Professor("Joseph", "jos#ntu.edu.sg", 67909999);
// al is an array list containing Professor objs
al.add(p1);
// write Professor record/s to file.
TextDB.saveProfessors(filename, al);
} catch (IOException e) {
System.out.println("IOException > " + e.getMessage());
}
}
UPDATE after comment:
public static void main(String[] aArgs) {
TextDB txtDB = new TextDB();
String filename = "professor.txt";
try {
//check if the file exist
File oFile = new File(filename);
if(!oFile.exist()) {
oFile.mkdirs(); //optional
oFile.createNewFile();
}
// read file containing Professor records.
ArrayList al = TextDB.readProfessors(filename);
for (int i = 0; i < al.size(); i++) {
Professor prof = (Professor) al.get(i);
System.out.println("Name " + prof.getName());
System.out.println("Contact " + prof.getContact());
}
Professor p1 = new Professor("Joseph", "jos#ntu.edu.sg", 67909999);
// al is an array list containing Professor objs
al.add(p1);
// write Professor record/s to file.
TextDB.saveProfessors(filename, al);
} catch (IOException e) {
System.out.println("IOException > " + e.getMessage());
}
}

Extract Integer part value which is only ID in given file

I have written a program to extract all integer value in the file and find the duplicate integer. But I want only those Integer value which is like ID="****.." / id="****..". I don't want to consider "dependsOnPresenceOf" value whatever it is.
My File is : for example
<line id="24867948" dependsOnPresenceOf="7417840">
<element text="Card Balance " id="18829409" dependsOnPresenceOf="28696224" />
<line id="2597826922" dependsOnPresenceOf="200114712343">
<methodElement fixedWidth="17" precededBySpace="false" id="418710522">
<line id="24867948" dependsOnPresenceOf="10565536">
<element text=" Cert. Number:" id="23917950" dependsOnPresenceOf="10565536" />
<line id="24867948" dependsOnPresenceOf="10565536">
<element text=" Cert. Number:" id="23917950" dependsOnPresenceOf="10565536" />
My Program is below which i have written to extract Integer value only :
public class DuplicateIDPicker {
protected static final Logger logger = Logger
.getLogger(com.aspire.pos.DuplicateIDPicker.class);
public static String finalContent = "";
public static void main(String[] args) throws FileNotFoundException {
String content = "";
/* Set location of the file as format below */
String path = "D://TASK/DuplicateFinder/OriginalFile/";
/* Set file name to be evaluate with extension */
String fileName = "SSLItems.bpt";
File f = new File(path.concat(fileName));
try {
content = readFile(f);
String extractedInteger = content.replaceAll("\\D+", " ");
String[] arrayOfID = findAllIDInArray(extractedInteger);
System.out.println("***********************");
HashSet<String> set = new HashSet<String>();
HashSet<String> newSet = new HashSet<String>();
System.out.println("Duplicate ID's found :");
for (String arrayElement : arrayOfID) {
if (!set.add(arrayElement)) {
// System.out.println("Duplicate Element is : "+arrayElement);
newSet.add(arrayElement);
}
}
System.out.println("-----------------------");
/* here are all Duplicate Id */
System.out.println(newSet);
} catch (IOException e) {
logger.error(e.getMessage());
}
}
#SuppressWarnings("resource")
public static String readFile(File f) throws IOException {
String data = "";
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
while ((data = br.readLine()) != null) {
// Print the content on the console
finalContent = finalContent + data;
}
return finalContent;
}
public static String[] findAllIDInArray(String str) {
String[] value = str.split(" ");
return value;
}
}
you can do content.replaceAll("dependsOnPresenceOf=\"\\d+\"", ""); to remove these unwanted strings
Here is a working solution that makes use of:
1) Java 7 read entire file in one line
2) Matcher ability to sequentially find occurences that match the expression
3) regex capturing group to get the desired numeric value
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DuplicateIDPicker
{
public static void main(String[] args)
{
/* Set location of the file as format below */
String path = "C://Temp/";
/* Set file name to be evaluate with extension */
String fileName = "in.txt";
Set<String> all = new HashSet<>();
Set<String> duplicates = new HashSet<>();
String regex = "(id|ID)\\=\"" // attribute name + quoted equal and quotation
+ "(\\d+)" // id value marked as (capturing group)
+ "\""; // closing quotation
try {
String content = readFile(path + fileName);
Matcher m = Pattern.compile(regex).matcher(content);
while (m.find()) {
String idValue = m.group(2);
if (!all.add(idValue)) duplicates.add(idValue);
}
System.out.println(duplicates);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String readFile(String fileFullPath) throws IOException
{
return new String(Files.readAllBytes(Paths.get(fileFullPath)));
}
}
This one is another solution to solve my problem.
public class DuplicateIDPicker {
protected static final Logger logger = Logger
.getLogger(com.aspire.pos.DuplicateIDPickerOld.class);
public static String finalContent = "";
public static void main(String[] args) throws FileNotFoundException,
IOException {
String content = "";
String[] arrayOFId = {};
String[] listOfID = {};
HashSet<String> set = new HashSet<String>();
HashSet<String> newSet = new HashSet<String>();
/* Set location of the file as format below */
String path = "D://TASK/DuplicateFinder/OriginalFile/";
/* Set file name to be evaluate with extension */
String fileName = "SSLPickupDeliveryOrderReceipt.txt";
File f = new File(path.concat(fileName));
content = readFile(f);
arrayOFId = findAllIDInString(content);
listOfID = extractIDOnly(arrayOFId);
System.out.println("***********************");
System.out.println("Duplicate ID's found :");
for (String arrayElement : listOfID) {
if (!set.add(arrayElement)) {
newSet.add(arrayElement);
}
}
System.out.println("-----------------------");
/* Duplicate Id stored in a Set : */
System.out.println(newSet);
}
/*
* This method is implemented to read file and
* return content in String format
*/
public static String readFile(File f) {
String data = "";
try {
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
while ((data = br.readLine()) != null) {
finalContent = finalContent + data;
}
br.close();
} catch (IOException e) {
logger.error(e.getMessage());
}
return finalContent;
}
/*
* This method is implemented to get Array string
* on the basis of '"'
*/
public static String[] extractIDOnly(String[] arr) {
ArrayList<String> listOfID = new ArrayList<String>();
for (int i = 0; i < arr.length; i++) {
String newString = arr[i];
String[] finalString = {};
for (int j = 0; j < newString.length();) {
finalString = newString.split("\"", 3);
for (int k = 1; k < finalString.length;) {
listOfID.add(finalString[1]);
break;
}
break;
}
}
return (String[]) listOfID.toArray(new String[listOfID.size()]);
}
/*
* This method is implemented to split the ID part only
*/
public static String[] findAllIDInString(String str) {
String[] value = str.split("id=");
return value;
}
}

database does not storing the content between angular brackets "<>"

I am using this java code to insert a txt file (which contain a java program) into MySQL database:
public static void main(String[] args) throws Exception {
String fileName = "copyEvens.txt";
FileInputStream fis = null;
PreparedStatement pstmt = null;
Connection conn = null;
try {
conn = getConnection();
conn.setAutoCommit(false);
File file = new File(fileName);
fis = new FileInputStream(file);
pstmt = conn.prepareStatement("insert into code_table(language, code, passkey, program_name) values (?, ?, ?, ?)");
pstmt.setString(1, "java");
pstmt.setAsciiStream(2, fis, (int) file.length());
pstmt.setString(3, "ved");
pstmt.setString(4, "copyEvens");
pstmt.executeUpdate();
conn.commit();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
} finally {
pstmt.close();
fis.close();
conn.close();
}
}
the txt file contain this program :
import java.util.Scanner;
public class copyEvens
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
String str =in.nextLine();
int n = in.nextInt();
String []token = str.split(" ");
int array[] = new int[token.length];
for(int i=0; i<token.length; i++)
{
array[i] = Integer.parseInt(token[i]);
}
copyEvens obj = new copyEvens();
int result[] = obj.copyEvens(array, n);
for(int i: result)
{
System.out.print(i + " ");
}
System.out.println();
}
public int[] copyEvens(int[] nums, int count)
{
int l = 0;
int temp[] = new int[count];
for(int i=0; i<nums.length; i++)
{
if(nums[i]%2 == 0)
{
temp[l] = nums[i];
if(l!=(count-1))
l++;
else
break;
}
}
return temp;
}
}
but in the database it is not storing the full program as it is mentioned just above. It is storing only this much program like this:
import java.util.Scanner;
public class copyEvens
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
String str =in.nextLine();
int n = in.nextInt();
String []token = str.split(" ");
int array[] = new int[token.length];
**for(int i=0; i**
After analyzing this I found that the program does not storing the things between this "<" ">" angular brackets. As, after this "for(int i=0; i" it should be "for(int i=0; i<token.length; i++)" and more..
Kindly help on this why it is not storing the content between angular brackets "<>".
You can try to dump the code directly into the database. If it is inserted as you expect (which there is absolutely no reason it shouldn't) then you will need to escape your data before inserting it. PHP has a htmlspecialchars function that does this for you but you will need to find an equivalent library that does this for Java - I had a quick scan online and found some messy code that does this but it was far too shoddy for me to recommend. to anyone :).

Issue with text file conversion to arraylist

I apologize in advance if the solution is relatively obvious; however, the AP compsci curriculum at my highschool included practically no involvement with IO or file components. I've been trying to write an elementary flashcard program - thus it would be much more practical to read strings off a text file than add 100 objects to an array. My issue is that when I go to check the size and contents of the ArrayList at the end, it's empty. My source code is as follows:
public class IOReader
{
static ArrayList<FlashCard> cards = new ArrayList<FlashCard>();
static File file = new File("temp.txt");
public static void fillArray() throws FileNotFoundException, IOException
{
FileInputStream fiStream = new FileInputStream(file);
if(file.exists())
{
try( BufferedReader br = new BufferedReader( new InputStreamReader(fiStream) )
{
String line;
String[] seperated;
while( (line = br.readLine()) != null)
{
try
{
seperated = line.split(":");
String foreign = seperated[0];
String english = seperated[1];
cards.add( new FlashCard(foreign, english) );
System.out.println(foreign + " : " + english);
}
catch(NumberFormatException | NullPointerException | ArrayIndexOutOfBoundsException e)
{
e.printStackTrace();
}
finally{
br.close();
}
}
}
}
else{
System.err.print("File not found");
throw new FileNotFoundException();
}
}
public static void main(String[] args)
{
try{
fillArray();
}
catch (Exception e){}
for(FlashCard card: cards)
System.out.println( card.toString() );
System.out.print( cards.size() );
}
}
My text file looks as thus:
Volare : To Fly
Velle : To Wish
Facere : To Do / Make
Trahere : To Spin / Drag
Odisse : To Hate
... et alia
My FlashCard class is very simplistic; it merely takes two Strings as parameter. The issue though is that the output whenever I run this is that nothing is printed except for the 0 printed in the main method, indicating that the ArrayList is empty. I thank you in advance for any help, as any would be appreciated.
Some point to consider:
in your fillArray() is good to throws exceptions and caught them inside agent
portion of your program which is main(), so your code in fillArray() will be more
readable and you will not hide the exceptions.
I do not think there is any need to check whether the file exist because if it does not
exist, the exception will be throw and main() function will be use it.
I use Igal class instead of FlashCard class which is as same as your FlashCard class
Code for Igal Class:
public class Igal {
private String st1;
private String st2;
public Igal(String s1, String s2){
st1 = s1;
st2 = s2;
}
/**
* #return the st1
*/
public String getSt1() {
return st1;
}
/**
* #param st1 the st1 to set
*/
public void setSt1(String st1) {
this.st1 = st1;
}
/**
* #return the st2
*/
public String getSt2() {
return st2;
}
/**
* #param st2 the st2 to set
*/
public void setSt2(String st2) {
this.st2 = st2;
}
#Override
public String toString(){
return getSt1() + " " + getSt2();
}
}
Code:
static List<Igal> cards = new ArrayList<>();
static File file = new File("C:\\Users\\xxx\\Documents\\NetBeansProjects\\Dictionary\\src\\temp.txt");
public static void fillArray() throws FileNotFoundException, IOException {
FileInputStream fiStream = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fiStream));
String line;
String[] seperated;
while ((line = br.readLine()) != null) {
seperated = line.split(":");
String foreign = seperated[0];
String english = seperated[1];
System.out.println(foreign + " : " + english);
Igal fc = new Igal(foreign, english);
cards.add(fc);
}
}
public static void main(String[] args) {
try {
fillArray();
} catch (IOException e) {
System.out.println(e);
}
System.out.println("------------------");
for (Igal card : cards) {
System.out.println(card.toString());
}
System.out.print("the size is " + cards.size()+"\n");
temp.txt content are as follows
Volare : To Fly
Velle : To Wish
Facere : To Do / Make
Trahere : To Spin / Drag
Odisse : To Hate
output:
------------------
Volare To Fly
Velle To Wish
Facere To Do / Make
Trahere To Spin / Drag
Odisse To Hate
the size is 5

Scanner from file doesn't seem to be reading file

I'm doing a Phone Directory project and we have to read from a directory file telnos.txt
I'm using a Scanner to load the data from the file telnos.txt, using a loadData method from a previous question I asked here on StackOverflow.
I noticed attempts to find a user always returned Not Found, so I added a few System.out.printlns in the methods to help me see what was going on. It looks like the scanner isn't reading anything from the file. Weirdly, it is printing the name of the file as what should be the first line read, which makes me think I've missed something very very simple here.
Console
run:
telnos.txt
null
loadData tested successfully
Please enter a name to look up: John
-1
Not found
BUILD SUCCESSFUL (total time: 6 seconds)
ArrayPhoneDirectory.java
import java.util.*;
import java.io.*;
public class ArrayPhoneDirectory implements PhoneDirectory {
private static final int INIT_CAPACITY = 100;
private int capacity = INIT_CAPACITY;
// holds telno of directory entries
private int size = 0;
// Array to contain directory entries
private DirectoryEntry[] theDirectory = new DirectoryEntry[capacity];
// Holds name of data file
private final String sourceName = "telnos.txt";
File telnos = new File(sourceName);
// Flag to indicate whether directory was modified since it was last loaded or saved
private boolean modified = false;
// add method stubs as specified in interface to compile
public void loadData(String sourceName) {
Scanner read = new Scanner("telnos.txt").useDelimiter("\\Z");
int i = 1;
String name = null;
String telno = null;
while (read.hasNextLine()) {
if (i % 2 != 0)
name = read.nextLine();
else
telno = read.nextLine();
add(name, telno);
i++;
}
}
public String lookUpEntry(String name) {
int i = find(name);
String a = null;
if (i >= 0) {
a = name + (" is at position " + i + " in the directory");
} else {
a = ("Not found");
}
return a;
}
public String addChangeEntry(String name, String telno) {
for (DirectoryEntry i : theDirectory) {
if (i.getName().equals(name)) {
i.setNumber(telno);
} else {
add(name, telno);
}
}
return null;
}
public String removeEntry(String name) {
for (DirectoryEntry i : theDirectory) {
if (i.getName().equals(name)) {
i.setName(null);
i.setNumber(null);
}
}
return null;
}
public void save() {
PrintWriter writer = null;
// writer = new PrintWriter(FileWriter(sourceName));
}
public String format() {
String a;
a = null;
for (DirectoryEntry i : theDirectory) {
String b;
b = i.getName() + "/n";
String c;
c = i.getNumber() + "/n";
a = a + b + c;
}
return a;
}
// add private methods
// Adds a new entry with the given name and telno to the array of
// directory entries
private void add(String name, String telno) {
System.out.println(name);
System.out.println(telno);
theDirectory[size] = new DirectoryEntry(name, telno);
size = size + 1;
}
// Searches the array of directory entries for a specific name
private int find(String name) {
int result = -1;
for (int count = 0; count < size; count++) {
if (theDirectory[count].getName().equals(name)) {
result = count;
}
System.out.println(result);
}
return result;
}
// Creates a new array of directory entries with twice the capacity
// of the previous one
private void reallocate() {
capacity = capacity * 2;
DirectoryEntry[] newDirectory = new DirectoryEntry[capacity];
System.arraycopy(theDirectory, 0, newDirectory,
0, theDirectory.length);
theDirectory = newDirectory;
}
}
ArrayPhoneDirectoryTester.java
import java.util.Scanner;
public class ArrayPhoneDirectoryTester {
public static void main(String[] args) {
//create a new ArrayPhoneDirectory
PhoneDirectory newTest = new ArrayPhoneDirectory();
newTest.loadData("telnos.txt");
System.out.println("loadData tested successfully");
System.out.print("Please enter a name to look up: ");
Scanner in = new Scanner(System.in);
String name = in.next();
String entryNo = newTest.lookUpEntry(name);
System.out.println(entryNo);
}
}
telnos.txt
John
123
Bill
23
Hello
23455
Frank
12345
Dkddd
31231
In your code:
Scanner read = new Scanner("telnos.txt");
Is not going to load file 'telnos.txt'. It is instead going to create a Scanner object that scans the String "telnos.txt".
To make the Scanner understand that it has to scan a file you have to either:
Scanner read = new Scanner(new File("telnos.txt"));
or create a File object and pass its path to the Scanner constructor.
In case you are getting "File not found" errors you need to check the current working directory. You could run the following lines and see if you are indeed in the right directory in which the file is:
String workingDir = System.getProperty("user.dir");
System.out.println("Current working directory : " + workingDir);
You need to also catch the FileNotFoundException in the function as follows:
public void loadData(String sourceName) {
try {
Scanner read = new Scanner(new File("telnos.txt")).useDelimiter("\\Z");
int i = 1;
String name = null;
String telno = null;
while (read.hasNextLine()) {
if (i % 2 != 0)
name = read.nextLine();
else {
telno = read.nextLine();
add(name, telno);
}
i++;
}
}catch(FileNotFoundException ex) {
System.out.println("File not found:"+ex.getMessage);
}
}
You are actually parsing the filename not the actual file contents.
Instead of:
new Scanner("telnos.txt")
you need
new Scanner( new File( "telnos.txt" ) )
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

Categories