I'm working on a project that requires me to import a text file, read the file, and sort the words in different ways(i.e. ascending order, unique words, etc...). So far, I've been able to import the file and have it print, that it, until I added the commands to sort the list into lines and words.
I've used a buffered reader to store the lines and the words, but upon execution, I don't know if the data has been stored in the separate arraylists, and the console doesn't print the number of words stored in ArrayList wordList.
Where am I going wrong here?
Here is my code so far:
public static void main(String[] args)throws IOException{ if(args.length == 0){ System.out.println("Error, usage: java ClassName inputfile"); System.exit(1); } File randomText = new File(args[0]); if(randomText.exists() && randomText.isFile()){ processFile(randomText); } else{ System.err.println("ERROR: file does not exist"); System.exit(1); } } public static void processFile(File randomText)throws IOException, FileNotFoundException{ ArrayList<String> lineList = new ArrayList<String>(); ArrayList<String> wordList = new ArrayList<String>(); BufferedReader br = new BufferedReader(new FileReader(randomText)); StringBuffer sb = new StringBuffer(); String line; while((line=br.readLine()) != null){ sb.append(line); sb.append("\n"); lineList.add(line); } while((line = br.readLine()) != null){ wordList = new ArrayList<String>(Arrays.asList(line.split(" |."))); } System.out.println("Total number of words in the file: " + wordList.size()); br.close(); } https://stackoverflow.com/questions/67051841/java-storing-lines-and-words-into-separate-arraylists-unable-to-print-results April 12, 2021 at 10:07AM
没有评论:
发表评论