I am trying to scan through text files and add them to a map, the map and everything is working. However, the scanner seems to be stopping when it comes to a 'enter' in the text file, or a blank line. This is my problem
here is my block of code for the scanner/mapper
class OneButtonListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent evt)
{
final JFileChooser oneFC = new JFileChooser();
oneFC.showOpenDialog(AnalysisFrame.this);
String newLine = null;
oneFC.getName(null);
int returnVal = 0;
File fileOne = oneFC.getSelectedFile();
Scanner input = null;
try {
input = new Scanner(fileOne);
}
catch (FileNotFoundException ex) {
Logger.getLogger(AnalysisFrame.class.getName()).log(Level.SEVERE, null,
ex);
}
inputText = input.nextLine();
String[] words = inputText.split("[ \n\t\r,.;:!?(){}]");
for(int i = 0; i < words.length; i++){
key = words[i].toLowerCase();
if (words[i].length() > 1){
if (mapOne.get(key) == null){
mapOne.put(key, 1);
}
else {
value1 = mapOne.get(key).intValue();
value1++;
apOne.put(key, value1);
}
}
}
}
}
Thanks for any help!
You should scan inside a loop until it reaches the end of the file, for example:
StringBuilder builder = new StringBuilder();
while(input.hasNextLine()){
builder.append(input.nextLine());
builder.append(" "); // might not be necessary
}
String inputText = builder.toString();
An alternative to using split could be to use a Delimiter with the Scanner and use hasNext() and next() instead of hasNextLine() and nextLine(). Try it out, see if it works.
For example:
scanner.useDelimiter("[ \n\t\r,.;:!?(){}]");
ArrayList<String> tokens = new ArrayList<String>();
while(scanner.hasNext()){
tokens.add(scanner.next());
}
String[] words = tokens.toArray(new String[0]); // optional
Also on a side note, it's not necessary to create the JFileChooser everytime:
class OneButtonListener implements ActionListener
{
private final JFileChooser oneFC = new JFileChooser();
#Override
public void actionPerformed(ActionEvent evt)
{
Not having worked with Java in a very long time I may be way off, but it looks like you call inputText = input.nextLine(); exactly once, so it makes sense that you're only getting one line. Presumably you want to call nextLine() in a loop so that it keeps giving you lines until it gets to the end of the file.
String contentsOfWholeFile = new Scanner(file).useDelimiter("\\Z").next();
In split("[ \n\t\r,.;:!?(){}]")
add \f
Related
Basically, I had to create a scanner for a given file and read through the file (the name is input through the terminal by the user) once counting the number of lines in the file. Then after, I had to create an array of objects from the file, of the correct size (where the num of lines comes in). Then I had to create another scanner for the file and read through it again, storing it in the array I created. And lastly, had to return the array in the method.
My problem is I cannot seem to get the second scanner to actually store the file objects in the array.
I've tried using .nextLine inside a for loop that also calls the array, but it doesn't seem to be working.
public static Data[] getData(String filename) {
Scanner input = new Scanner(new File(filename));
int count = 0;
while (input.hasNextLine()) {
input.nextLine();
count++;
}
System.out.println(count);
Data[] data = new Data[count];
Scanner input1 = new Scanner(new File(filename));
while (input1.hasNextLine()) {
for (int i = 0; i < count; i++) {
System.out.println(data[i].nextLine);
}
}
return data;
}
I expect the output to successfully read the input file so that it can be accessed by other methods that I have created (not shown).
You should definitely use an IDE if you don't have one, try intellij... There you have autocompletion and syntax checking and much more.
It is not clear what you want to do in your for loop, because there are several mistakes, for example the readline() function works only with the scanner objekt, so you can do input.nextline() or input1.nextline()`...
so I just show you, how you can get the Data from a file with Scanner:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Readfile {
public static void getData(String filename) throws FileNotFoundException {
ArrayList<String> test = new ArrayList<>(); //arraylist to store the data
Scanner inputSc = new Scanner(new File(filename)); //scanner of the file
while (inputSc.hasNextLine()) {
String str = inputSc.nextLine();
System.out.println(str); //print the line which was read from the file
test.add(str); //adds the line to the arraylist
//for you it would be something like data[i] = str; and i is a counter
}
inputSc.close();
}
public static void main(String[] args) {
try {
getData("/home/user/documents/bla.txt"); //path to file
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
You don't need to read thru the file twice - just use an ArrayList to hold the data that's coming in from the file, like this, and then return Data[] at the end:
public static Data[] getData(String filename) {
List<Data> result = new ArrayList<>();
try (Scanner input = new Scanner(new File(filename))){
while (input.hasNextLine()) {
Data data = new Data(input.nextLine());
result.add(data);
}
}
return result.toArray(new Data[0]);
}
Not clear what Data.class do you mean, if you switch it to String, the problem obviously would be in this line
System.out.println(data[i].nextLine);
if you want to assign and print simultaneously write this
for (int i = 0; i < count; i++) {
data[i] = input1.next();
System.out.println(data[i]);
}
and dont forget to close your Scanners, better use try-with-resources.
If your Data is your custom class you'd better learn about Serialization-Deserialization
Or use some ObjectMapper-s(Jackson, for example) to store your class instances and restore them.
Your way of opening the file just to count the lines and then again looping through its lines to store them in the array is not that efficient, but it could be just a school assignment.
Try this:
public static Data[] getData(String filename) {
Scanner input = null;
try {
input = new Scanner(new File(filename));
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
int count = 0;
while (input.hasNextLine()) {
input.nextLine();
count++;
}
input.close();
System.out.println(count);
Data[] data = new Data[count];
try {
input = new Scanner(new File(filename));
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
for (int i = 0; i < count; i++) {
Data d = new Data(input.nextLine(), 0, 0);
data[i] = d;
System.out.println(data[i].name);
}
input.close();
return data;
}
After the 1st loop you must close the Scanner and reopen it so to start all over from the first line of the file.
I am trying to read integers from a text file but I failed.
(It fails to read even the first integer)
public void readFromFile(String filename) {
File file = new File(filename);
try {
Scanner scanner = new Scanner(file);
if (scanner.hasNextInt()) {
int x = scanner.nextInt();
}
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("File to load game was not found");
}
}
The error I get is: NoSuchElementException.
The file looks like this:
N,X1,Y1,X2,Y2,X3,Y3
While n equals 3 in this example.
I call this method a in the main method like this:
readFromFile("file.txt");
I am not sure whether you would like to display only the integers after separating them from the string. If that is the case, I would suggest you to use BufferedInputStream.
try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)))){
String input = br.readLine();
int count = 0;
for(int i = 0; i < input.length()- 1; i++){
if(isNumeric(input.charAt(i))){
// replace the Sysout with your own logic
System.out.println(input.charAt(i));
}
}
} catch (IOException ex){
ex.printStackTrace();
}
where isNumeric can be defined as follows:
private static boolean isNumeric(char val) {
return (val >= 48 && val <=57);
}
Scanneruses whitespace as the default delimiter. You can change that with useDelimiter See here: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Here is my code:
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
public class Filter{
Message myMessage;
Scanner input;
Scanner input2;
String sender;
String subject;
String emailMIN;
String line;
String line2;
ArrayList<String> blacklist = new ArrayList<String>();
ArrayList<String> keywords = new ArrayList<String>();
ArrayList<String> subjectWords = new ArrayList<String>();
ArrayList<String> emails = new ArrayList<String>();
//String[] lines;
File SpamMessage;
File inFile;
File inFile2;
File tempFile;
String[] lines;
public Filter(Message m,String blacklistFile, String keywordFile, String Spam)throws IOException{
inFile = new File(blacklistFile);
inFile2 = new File(keywordFile);
input = new Scanner (inFile);
input2 = new Scanner (inFile2);
myMessage =m;
SpamMessage=new File(Spam);
}
public void filter() throws IOException{
PrintWriter output = new PrintWriter(SpamMessage);
while(input.hasNextLine()){
line = input.nextLine();
//System.out.println(line);
if(line!=null)
blacklist.add(line);
}
while(input2.hasNextLine()){
line2 = input2.nextLine();
//System.out.println(line2);
if(line!=null)
keywords.add(line2);
}
emails=myMessage.getEmails();
// System.out.println(emails.size() + emails.get(1));
for(int i = 0; i < emails.size(); i++){
// boolean isSpam = false;
lines = emails.get(i).split("\n");
// System.out.println(lines[5] + lines[7]);
sender = lines[2].substring(lines[2].indexOf('<'), lines[2].indexOf('>'));
//` System.out.println(sender);
emailMIN = lines[6].substring(lines[6].indexOf('<'), lines[6].indexOf('>'));
// System.out.println(emailMIN);
for(int j =0; j<lines.length; j++)
{
if(j==2)
{
for(String blacklist2: blacklist)
{
// System.out.println(blacklist2);
if(lines[j].contains(blacklist2))
{
output.println(emailMIN);
}
// output.close();
}
}
if(j==5 || j>=7)
{
// System.out.println(keywords.size());
for(String keywords2: keywords)
{
// System.out.println(keywords2);
if(lines[j].contains(keywords2))
{
output.println(emailMIN);
}
// output.close();
}
}
//addKeywords();
}
}
output.close();
addKeywords();
}
public void addKeywords() throws IOException
{
tempFile = new File("tempFile.txt");
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
for(int i=0; i<lines.length; i++)
{
if(i==5){
String[] words = lines[i].split(" ");
for(String word: words){
if(word.length()>=6){
subjectWords.add(word +"\n");
//System.out.println(subjectWords);
}
}
keywords.addAll(subjectWords);
pw.println(keywords);
}
}
pw.close();
if (!inFile2.delete()) {
//System.out.println("Could not delete file");
return;
}
// Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile2)){
//System.out.println("Could not rename file");
}
}
}
I'm trying to update the list of words in the keywords txt file right now it does update it but it puts it in the format [generic, pharmacy, little, inside]
Which is wrong because then if I run my code again it is searching if the file contains [generic, pharmacy, little, inside] and I need it to search for every word not the plus a comma or brace. So basically I want it to copy the words in a list format like this
generic
pharmacy
little
inside
That way it searches for each individual word. I figured out how to do this part. Now, how do I add the senders to a different text file? Also is there a way to modify this so it doesn't add the same keywords twice? Thanks
It is because you are writing an array to the file which causes the toString method of it to be called. Write every single item instead.
Instead of pw.println(keywords);
Do:
for (String keyword : keywords)
{
pw.println(keyword.trim());
}
Or, if every word contains \n already, this should work
for (String keyword : keywords)
{
pw.print(keyword);
}
Instead of doing:
pw.println(keywords);
you should instead loop through the array and add each line individually.
for(int i = 0; i < keywords.length; i++) {
pw.println(keywords[i]);
}
That was because you are printing an ArrayList object. In your code, keywords is instance of the List and which would you give you an output of [aa,bb] . More over you would get duplicate words since these list instance are class variables, and printed inside a loop
keywords.addAll(subjectWords);
pw.println(keywords);
Either you can loop around keywords outside the for loop or print the word before adding to list.
Consider this code:
private static void colourRead(String s) throws IOException {
FileReader readhandle = new FileReader("C:\\****\\****");
BufferedReader br = new BufferedReader(readhandle);
String line = null;
while ((line = br.readLine()) != null) {
ColourInput(); //there's an error here
}
br.close();
readhandle.close();
}
private static void ColourInput(String s) {
char letter;
String fullWord;
Scanner kb = new Scanner(System.in);
System.out.print("Enter whatever: ");
fullWord = kb.nextLine();
System.out.println(fullWord);
for (int i = 0; i < fullWord.length(); i++) {
letter = fullWord.charAt(i);
switch (Character.toUpperCase(letter)) {
case 'A': {
Blue();
}
break;
}
}
}
Is it possible for me to carry the
line
variable from the colourRead method, and somehow assign it to the
fullWord
variable in the ColourInput() method?
I'm trying to read a text file, and output certain colours associated to each letter. I don't want to create a new switch statement in the colourRead method because apparently, this is a bad programming practice.
Any help please?
If you're still unsure of what I'm asking I'll re-edit
EDIT: The problem is that after calling the ColourInput(line) method, the Scanner method comes in to work (original code). I don't want to remove my Scanner method, I want it to 'skip' the scanner method, and continue into the for loop and switch statements.
You're not passing the string to your call of ColourInput
Try
ColourInput(line);
It is also worth mentioning that your code that reads the file is not safe, you should try to read the file, catch the IOException and close the file in a finally clause, if your code crashes somewhere in the while loop your file might remain open
If I understand correctly you want to be able to repeat the functionality of the ColourInput method with the results of the the ColourRead method.
private static void colourRead() throws IOException
{
FileReader readhandle = new FileReader("C:\\****\\****");
BufferedReader br = new BufferedReader(readhandle);
String line = null;
while((line = br.readLine()) != null)
{
ColourText(line); //there's an error here
}
br.close();
readhandle.close();
}
private static void ColourInput()
{
String fullWord;
Scanner kb = new Scanner(System.in);
System.out.print("Enter whatever: ");
fullWord = kb.nextLine();
System.out.println(fullWord);
ColourText(fullWord);
}
private static void ColourText(String text)
{
char letter;
for (int i = 0; i < text.length(); i++)
{
letter = text.charAt(i);
switch(Character.toUpperCase(letter))
{
case 'A':
{
Blue();
}
break;
}
}
This would let you color the text whether it is read from the file or input from the keyboard(using the ColourText method to change the color). But as other people have mentioned you should add to the file reading code as well.
Edit: You could also remove the String s variables from the first two methods since they are not being used in the methods anywhere.
I have a list of Strings in single column. I want to make three columns from these string and then print the ouput to another file. How do I do this?
Here is what I've tried so far:
ArrayList<String> list=new ArrayList<String>();
File file = new File("f://file.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
My input data:
City
Gsk
Relocation
sripallu
here
jrajesh
gurgaon
unitech
StatisticsThreads
WizOty
LTDParsvnathK
Quotesby
newest
PMaashuktr
My expected output:
City Gsk Relocation
sripallu here jrajesh
gurgaon unitech StatisticsThreads
WizOty LTDParsvnathK Quotesby
newest PMaashuktr Loans
.
.
.
.
.
.
.
You can structured your requirement in class like Output and make a list of Output.
public class Output{
private String str1;
private String str2;
private String str3;
<geter & setter method>
}
...
ArrayList<Output> list=new ArrayList<Output>();
int i=-1; Output op =null;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();i = ++i%3;
if(i==0){
op = new Output();
op.setStr1(line);
}else if(i==1)
op.setStr2(line);
else
op.setStr3(line);
}
I took your code and modified it a little:
File file = new File("f://file.txt");
try {
Scanner scanner = new Scanner(file);
int itemsOnRow = 0;
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
System.out.print (line + " ");
itemsOnRow++;
if (itemsOnRow == 3)
{
itemsOnRow = 0;
System.out.println ();
}
}
scanner.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
You should actually try to implement it next time. If you fail but post the code that you wrote, then it's easier for the people here to help you.