I'd appreciate if somebody could have a look at this code and tell me where the problem is.
The program is meant to take a .txt file and split it in three different files: one with words of 1 to 4 letters, one with words of 5 to 7 and the last one with words of 8 letters onwards.
For some reason the program starts and does well (that is, behaves as expected) until it reaches about the middle of the original file. Then I get a NullPointerException: line 34.
Two of the destination files are OK and one is truncated.
Here is the code:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;


public class DictSplitter {
	File dict = new File("diccionario.txt");
	File easy = new File("easy.txt");
	File diff = new File("difficult.txt");
	File noWay = new File("xtreme.txt");

	public static void main(String[] args) throws IOException {
		DictSplitter ds = new DictSplitter();

		BufferedReader br = new BufferedReader(new FileReader(ds.dict));
		BufferedWriter bwE = new BufferedWriter(new FileWriter(ds.easy));
		bwE.write("Word length: up to 4 letters");
		bwE.newLine();
		BufferedWriter bwD = new BufferedWriter(new FileWriter(ds.diff));
		bwD.write("Word length: 5 to 7 letters");
		bwD.newLine();
		BufferedWriter bwNW = new BufferedWriter(new FileWriter(ds.noWay));
		bwNW.write("Word length: from 8 letters onwards");
		String tmp = "";
		int easyCount = 0, diffCount = 0, nwCount = 0;

		while (tmp != null) {
			tmp = br.readLine();
			//        System.out.println("tmp: " + tmp);
			int letters = tmp.length();
			switch (letters) {
			case 0:
			case 1:
			case 2:
			case 3:
			case 4:
				bwE.write(tmp);
				bwE.newLine();
				easyCount++;
				break;
			case 5:
			case 6:
			case 7:
				bwD.write(tmp);
				bwD.newLine();
				diffCount++;
				break;
			default:
				bwNW.write(tmp);
				bwNW.newLine();
				nwCount++;
				break;
			}
		}
		bwE.close();
		bwD.close();
		bwNW.close();
		System.out.println("easy: " + easyCount + "\t\tdifficult: " +
		                   diffCount + "\t\tnoWay: " + nwCount);
	}
}

Thank you in advance.

'tmp' string might be null. put a check like this after you do the 'readLine' and try

if(tmp != null)
{
//your code
}

Edited 7 Years Ago by Agni: n/a

Comments
thanks

The documentation for BufferedReader states the following ..."Returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached." When you reach the end of the file, the value is "null".

http://java.sun.com/j2se/1.5.0/docs/api/java/io/BufferedReader.html#readLine()

As Agni said, tmp is null which is why you are getting the NullPointerException. It happens because you try to do the following when tmp = null:

int letters = tmp.length();

You can use an "if" statement as Agni mentioned or just combine lines 31 and 32 as follows:

while ((tmp=br.readLine()) != null){

Hi, thanks to both. That solved the problem although I still don't quite understand.
Cgeier, the thing is, the NullPointerException doesn't come when it's finished reading the original file. It comes in the middle of the file and then continues reading until the end.

thank you,
here is the file

Attachments
aardvark
aardwolf
aaron
aback
abacus
abaft
abalone
abandon
abandoned
abandonment
abandons
abase
abased
abasement
abash
abashed
abate
abated
abatement
abates
abattoir
abattoirs
abbe
abbess
abbey
abbeys
abbot
abbots
abbreviate
abbreviated
abbreviates
abbreviating
abbreviation
abbreviations
abdicate
abdicated
abdicates
abdicating
abdication
abdomen
abdomens
abdominal
abduct
abducted
abducting
abduction
abductions
abductor
abductors
abducts
abe
abeam
abel
abele
aberdeen
aberrant
aberration
aberrations
abet
abets
abetted
abetting
abeyance
abhor
abhorred
abhorrence
abhorrent
abhors
abide
abided
abides
abiding
abidjan
abies
abilities
ability
abject
abjectly
abjure
abjured
ablate
ablates
ablating
ablation
ablative
ablaze
able
ablebodied
abler
ablest
abloom
ablution
ablutions
ably
abnegation
abnormal
abnormalities
abnormality
abnormally
aboard
abode
abodes
abolish
abolished
abolishes
abolishing
abolition
abolitionist
abolitionists
abomb
abominable
abominably
abominate
abominated
abomination
abominations
aboriginal
aborigines
abort
aborted
aborting
abortion
abortionist
abortionists
abortions
abortive
aborts
abound
abounded
abounding
abounds
about
above
abraded
abraham
abrasion
abrasions
abrasive
abrasively
abrasiveness
abrasives
abreast
abridge
abridged
abridgement
abridging
abroad
abrogate
abrogated
abrogating
abrogation
abrogations
abrupt
abruptly
abruptness
abscess
abscesses
abscissa
abscissae
abscissas
abscond
absconded
absconder
absconding
absconds
abseil
abseiled
abseiler
abseiling
abseils
absence
absences
absent
absented
absentee
absenteeism
absentees
absenting
absently
absentminded
absentmindedly
absentmindedness
absolute
absolutely
absoluteness
absolutes
absolution
absolutism
absolutist
absolutists
absolve
absolved
absolves
absolving
absorb
absorbed
absorbency
absorbent
absorber
absorbers
absorbing
absorbingly
absorbs
absorption
absorptions
absorptive
absorptivity
abstain
abstained
abstainer
abstainers
abstaining
abstains
abstemious
abstemiously
abstemiousness
abstention
abstentions
abstinence
abstinent
abstract
abstracted
abstractedly
abstracting
abstraction
abstractions
abstractly
abstracts
abstruse
abstrusely
absurd
absurder
absurdest
absurdist
absurdities
absurdity
absurdly
abundance
abundances
abundant
abundantly
abuse
abused
abuser
abusers
abuses
abusing
abusive
abusively
abusiveness
abut
abutment
abutments
abutted
abutting
abuzz
aby
abysmal
abysmally
abyss
abyssal
abysses
acacia
academe
academia
academic
academical
academically
academician
academicians
academics
academies
academy
acanthus
acapulco
accede
acceded
acceding
accelerate
accelerated
accelerates
accelerating
acceleration
accelerations
accelerator
accelerators
accelerometer
accelerometers
accent
accented
accenting
accents
accentuate
accentuated
accentuates
accentuating
accentuation
accept
acceptability
acceptable
acceptably
acceptance
acceptances
accepted
accepting
acceptor
acceptors
accepts
access
accessed
accesses
accessibility
accessible
accessing
accession
accessions
accessories
accessory
accidence
accident
accidental
accidentally
accidentprone
accidents
acclaim
acclaimed
acclaims
acclamation
acclamations
acclimatisation
acclimatise
acclimatised
acclimatising
accolade
accolades
accommodate
accommodated
accommodates
accommodating
accommodation
accommodations
accompanied
accompanies
accompaniment
accompaniments
accompanist
accompany
accompanying
accomplice
accomplices
accomplish
accomplished
accomplishes
accomplishing
accomplishment
accomplishments
accord
accordance
accorded
according
accordingly
accordion
accordionist
accordions
accords
accost
accosted
accosting
accosts
account
accountability
accountable
accountancy
accountant
accountants
accounted
accounting
accounts
accra
accredit
accreditation
accredited
accrediting
accredits
accreted
accretion
accretions
accrual
accruals
accrue
accrued
accrues
accruing
accumulate
accumulated
accumulates
accumulating
accumulation
accumulations
accumulative
accumulator
accumulators
accuracies
accuracy
accurate
accurately
accursed
accusal
accusals
accusation
accusations
accusative
accusatory
accuse
accused
accuser
accusers
accuses
accusing
accusingly
accustom
accustomed
accustoming
ace
aced
acentric
acerbic
acerbity
acers
aces
acetal
acetate
acetates
acetic
acetone
acetylene
ache
ached
aches
achievable
achieve
achieved
achievement
achievements
achiever
achievers
achieves
achieving
aching
achingly
achings
achromatic
achy
acid
acidic
acidification
acidified
acidify
acidifying
acidity
acidly
acidophiles
acidrain
acids
acknowledge
acknowledged
acknowledgement
acknowledgements
acknowledges
acknowledging
acknowledgment
acknowledgments
acme
acne
acolyte
acolytes
aconite
acorn
acorns
acoustic
acoustical
acoustically
acoustics
acquaint
acquaintance
acquaintances
acquainted
acquainting
acquaints
acquiesce
acquiesced
acquiescence
acquiescent
acquiescing
acquire
acquired
acquirer
acquirers
acquires
acquiring
acquisition
acquisitions
acquisitive
acquisitiveness
acquit
acquited
acquites
acquits
acquittal
acquittals
acquittance
acquitted
acquitting
acre
acreage
acres
acrid
acrimonious
acrimoniously
acrimony
acrobat
acrobatic
acrobatics
acrobats
acronym
acronyms
across
acrostic
acrostics
acrylic
acrylics
act
acted
acting
actings
actinides
action
actionable
actions
activate
activated
activates
activating
activation
activations
activator
activators
active
actively
actives
activism
activist
activists
activities
activity
actor
actors
actress
actresses
acts
actual
actualisation
actualise
actualised
actualities
actuality
actually
actuarial
actuaries
actuary
actuate
actuated
actuates
actuating
actuation
actuator
actuators
acuity
acumen
acupuncture
acupuncturist
acupuncturists
acute
acutely
acuteness
acuter
acutest
acyclic
adage
adages
adagio
adam
adamant
adamantly
adapt
adaptability
adaptable
adaptation
adaptations
adapted
adapter
adapters
adapting
adaptive
adaptively
adaptivity
adaptor
adaptors
adapts
add
added
addenda
addendum
adder
adders
addict
addicted
addiction
addictions
addictive
addictiveness
addicts
adding
addition
additional
additionally
additions
additive
additively
additives
addle
addled
addles
addling
address
addressability
addressable
addressed
addressee
addressees
addresses
addressing
adds
adduce
adduced
adduces
adducing
adelaide
aden
adenine
adenoid
adenoids
adenoma
adenomas
adept
adepts
adequacy
adequate
adequately
adhere
adhered
adherence
adherent
adherents
adherer
adherers
adheres
adhering
adhesion
adhesions
adhesive
adhesiveness
adhesives
adhoc
adiabatic
adiabatically
adieu
adieus
adieux
adios
adipose
adit
adjacency
adjacent
adjacently
adjectival
adjective
adjectives
adjoin
adjoined
adjoining
adjoins
adjourn
adjourned
adjourning
adjournment
adjourns
adjudge
adjudged
adjudges
adjudicate
adjudicated
adjudicates
adjudicating
adjudication
adjudications
adjudicator
adjudicators
adjunct
adjuncts
adjure
adjust
adjustable
adjusted
adjuster
adjusting
adjustment
adjustments
adjusts
adjutant
adlib
adlibs
adman
admen
admin
administer
administered
administering
administers
administrate
administrated
administrating
administration
administrations
administrative
administratively
administrator
administrators
admirable
admirably
admiral
admirals
admiration
admire
admired
admirer
admirers
admires
admiring
admiringly
admissibility
admissible
admission
admissions
admit
admits
admittance
admittances
admitted
admittedly
admitting
admix
admixture
admonish
admonished
admonishes
admonishing
admonishment
admonition
admonitions
admonitory
ado
adobe
adolescence
adolescent
adolescents
adonis
adopt
adopted
adopter
adopting
adoption
adoptions
adoptive
adopts
adorable
adorably
adoration
adore
adored
adorer
adorers
adores
adoring
adoringly
adorn
adorned
adorning
adornment
adornments
adorns
adrenal
adrenalin
adrenaline
adrift
adroit
adroitly
adroitness
adsorb
adsorbed
adsorption
adulation
adulatory
adult
adulterate
adulterated
adulterates
adulterating
adulteration
adulterations
adulterer
adulterers
adulteress
adulteresses
adulterous
adultery
adulthood
adults
adumbrate
adumbrated
adumbrating
advance
advanced
advancement
advancements
advancer
advances
advancing
advantage
advantaged
advantageous
advantageously
advantages
advent
advents
adventure
adventured
adventurer
adventurers
adventures
adventuring
adventurism
adventurous
adventurously
adverb
adverbial
adverbs
adversarial
adversaries
adversary
adverse
adversely
adversities
adversity
advert
adverted
advertise
advertised
advertisement
advertisements
advertiser
advertisers
advertises
advertising
adverts
advice
advices
advisability
advisable
advise
advised
advisedly
adviser
advisers
advises
advising
advisory
advocacy
advocate
advocated
advocates
advocating
adze
aegean
aegina
aegis
aeolian
aeon
aeons
aerate
aerated
aerates
aerating
aeration
aerator
aerial
aerially
aerials
aerify
aerobatic
aerobatics
aerobe
aerobes
aerobic
aerobically
aerobics
aerobraking
aerodrome
aerodromes
aerodynamic
aerodynamically
aerodynamics
aerofoil
aerofoils
aeronaut
aeronautic
aeronautical
aeronautics
aeroplane
aeroplanes
aerosol
aerosols
aerospace
aesop
aesthete
aesthetes
aesthetic
aesthetically
aestheticism
aestheticsy
afar
affability
affable
affably
affair
affairs
affect
affectation
affectations
affected
affectedly
affecting
affection
affectionate
affectionately
affections
affective
affects
afferent
affidavit
aff

The null is because it's reading past the last line of the file. So when it has read the last line the 'while' is true, then it reads the next line(one after last one) then when you access the length of tmp you get a nullpointer exception. re-write your loop to prevent that.

As a future strategy, try to put a lot of prints and you might be able to figure out such bugs very quickly.

This question has already been answered. Start a new discussion instead.