Reached end of file while parsing error - java

I created this code in Java but I am getting the following error:
"Reached end of file while parsing error".
Can someone please have a look at it?
import java.io.*;
import java.util.Scanner;
public class ParseTest {
public static void main(String args[]) throws IOException {
Set<String> positive = loadDictionary("PositiveWordsDictionary");
Set<String> negative = loadDictionary("NegativeWordsDictionary");
File file = new File("fileforparsing");
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
Scanner sc = new Scanner(br);
String word;
long positiveCount = 0;
long negativeCount = 0;
while (sc.hasNext()) {
word = sc.next();
if (positive.contains(word)) {
System.out.println("Found positive "+positiveCount+":"+word);
positiveCount++;
}
if (negative.contains(word)) {
System.out.println("Found negative "+positiveCount+":"+word);
negativeCount++;
}
}
br.close();
}
public static Set<String> loadDictionary(String fileName) throws IOException {
Set<String> words = new HashSet<String>();
File file = new File(fileName);
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
Scanner sc = new Scanner(br);
while (sc.hasNext()) {
words.add(sc.next());
}
br.close();
return words;
}
I have checked the curly braces error but nothing helps.

You are missing a curly brace. This is what your code should look like:
import java.io.*;
import java.util.Scanner;
public class ParseTest
{
public static void main(String args[]) throws IOException
{
Set<String> positive = loadDictionary("PositiveWordsDictionary");
Set<String> negative = loadDictionary("NegativeWordsDictionary");
File file = new File("fileforparsing");
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
Scanner sc = new Scanner(br);
String word;
long positiveCount = 0;
long negativeCount = 0;
while (sc.hasNext())
{
word = sc.next();
if (positive.contains(word))
{
System.out.println("Found positive "+positiveCount+":"+word);
positiveCount++;
}
if (negative.contains(word))
{
System.out.println("Found negative "+positiveCount+":"+word);
negativeCount++;
}
}
br.close();
}
public static Set<String> loadDictionary(String fileName) throws IOException
{
Set<String> words = new HashSet<String>();
File file = new File(fileName);
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
Scanner sc = new Scanner(br);
while (sc.hasNext())
{
words.add(sc.next());
}
br.close();
return words;
}
}
Line up your brackets, makes it much easier to read.

Related

How can I delete lines of data in textfile using java? eg. my textfile is data.txt

From read the line needed to be deleted by the user to delete it
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class Delete {
public static void main(String[] args) throws IOException {
File input = new File("data.txt");
FileReader fr = null;
Scanner ob = new Scanner(System.in);
// declare variable
String DeleteWord, str, newDeleteWord;
System.out.print("Enter word you want to delete: ");
DeleteWord = ob.nextLine();
newDeleteWord = (capitalize(DeleteWord));
try {
fr = new FileReader(input);
BufferedReader br = new BufferedReader(fr);
while ((str = br.readLine()) != null) {
if (str.contains(newDeleteWord)) {
System.out.println(str);
}
Scanner read = new Scanner(System.in);
int selection;
System.out.println("Confirm to delete his/her data?\n 1 for yes\n 2 for no");
selection = read.nextInt();
if (selection == 1)
if (str.contains(newDeleteWord)) {
str = "";
}
}
} finally {
fr.close();
}
}
public static String capitalize(String str1) {
if (str1 == null || str1.isEmpty()) {
return str1;
}
return str1.substring(0, 1).toUpperCase() + str1.substring(1);
}
}
How can I delete lines of data in textfile using java? eg. my textfile is data.txt
This is a possible solution:
File inputFile = new File("myFile.txt"); // File which we will read
File tempFile = new File("myTempFile.txt"); // The temporary file where we will write
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = yourString; // here is your line to remove
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim(); // we trim it and remove unecessary spaces
if(trimmedLine.equals(lineToRemove)) continue; // If it is equal to our line to remove then do not write it to our file!
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
inputFile.delete(); // we delete the file that we have so that we have no conflicts
boolean successful = tempFile.renameTo(inputFile);
OR
Reading all the lines in a list and filtering this list.
The quickest way is through Apache Commons-IO ( or you can implement it yourself)
Apache Commons:
List<String> lines = FileUtils.readLines(file);
List<String> updatedLines = lines.stream().filter(s -> !s.contains(searchString)).collect(Collectors.toList());
FileUtils.writeLines(file, updatedLines, false);

Java File Read in As Array

I am really stuck here, I can't seem to read in the arrays properly.
I can't seem to read in these arrays into columns. Looking for a solution to help me finally make an array out of these numbers.
public class TextFileInputAndOutput
{
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("USStateCapitalsSelected.txt"));
int lineCounter = 1;
String line;
while ((line = reader.readLine()) != null) {
// parse line using any method.
// example 1:
Scanner intScanner = new Scanner(line);
while (intScanner.hasNextLine()) {
String nextInt = intScanner.nextLine();
System.out.println(nextInt + "Herro");
if (intScanner.hasNextDouble() == true) {
Scanner scanner = new Scanner(line);
while (scanner.hasNextDouble()) {
String nextString = scanner.next();
System.out.println(nextString);
}
}
}
}
}
}
You can use com.google.common.io.Files:
Sample.txt:
nameA labA quizeA
nameB labB quizeB
Code:
public static void main(String[] args) throws Exception {
File myFile = new File("Sample.txt");
ArrayList<String> names = new ArrayList<String>();
ArrayList<String> labs = new ArrayList<String>();
ArrayList<String> quizes = new ArrayList<String>();
for (String line : Files.readLines(myFile, Charset.defaultCharset())) {
String[] cols = line.split(" ");
names.add(cols[0]);
labs.add(cols[1]);
quizes.add(cols[2]);
}
System.out.println(names);
System.out.println(labs);
System.out.println(quizes);
}
Tryb this
try{
File file = new File("filename");
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] temp = line.split(" ");
//add values to arraylist
names.add(temp[0]);
labs.add(temp[1]);
quizes.add(temp[2]);
}
}catch (Exception ex) {
ex.printStackTrace();
}

Infinite loop while using Scanner to read file Java

So I am trying to parse text files that could be in the form
words words words werdz words
or
words
words
words
words
words
Because of this, I decided to use Scanner instead of BufferedReader, and I'm not very experienced with using Scanner. I am trying to read a file and save to a Collection. Here is the main code and the supplementary methods.
main:
public static void main(String[] args) throws IOException {
LinkedList<String> unmodDict = readDict(new File(args[0]));
String[] unsorted = readUnsorted(new File(args[1]));
...
}
readDict()
public static LinkedList<String> readDict(File file) throws IOException {
//BufferedReader reader = new BufferedReader(new FileReader(file));
Scanner s = new Scanner(new FileReader(file));
String line = null;
LinkedList<String> ll = new LinkedList<>();
int count = 0;
while(s.hasNext()) {
ll.add(s.next());
}
// this loop seems to run finitely.
s.close();
return ll;
}
readUnsorted()
public static String[] readUnsorted(File file) throws IOException {
//BufferedReader reader = new BufferedReader(new FileReader(file));
Scanner reader = new Scanner(new FileReader(file));
int count = 0;
while (reader.hasNext()) {
count++;
}
reader.close();
// The above loop is running infinitely.
Scanner reader2 = new Scanner(new FileReader(file));
String line2 = null;
String[] unsortedWerdz = new String[count];
int i = 0;
while (reader2.hasNext()) {
unsortedWerdz[i] = reader2.next();
i++;
}
reader2.close();
return unsortedWerdz;
}
For some reason, the first while loop in the readUnsorted method is running infinitely but I can't see why since the first loop in the readDict method seems to run fine. Could someone advise me on what to do?
Thanks
It run's forever, since you check if there's a next String avaiable, but you don't retrieve it!
You need to get it via next() like this:
while (reader.hasNext()) {
reader.next();
count++;
}
Otherwise the Scanner will always point at the same (the first) element it reads and always report: Yes, there's another token in here!

inputfilestream to a String

I have the following logic to open a file:
Except what I want to do is not just print the file on the screen, but to take a line and store it to a String called test.
Can someone please help me with this ?
// fetch the file
String filename = "companySecret.txt";
String filepath = "C:\\";
String test;
java.io.FileInputStream fileInputStream = new java.io.FileInputStream(filepath + filename);
int i;
while ((i=fileInputStream.read()) != -1)
{
System.out.write(i);
}
fileInputStream.close();
I suggest you use the BufferedReader class and use the ReadLine method to extract the line from the file.
// fetch the file
String filename = "companySecret.txt";
String filepath = "C:\\";
String test;
java.io.FileReader fileInputReader = new java.io.FileReader(filepath + filename);
java.io.BufferedReader input = new java.io.BufferedReader( fileInputReader );
while ((test=input.readLine()) != null)
{
// Do something with the line...
}
fileInputStream.close();
Use Apache Commons IO library:
String fileContents = FileUtils.readFileToString(file);
http://commons.apache.org/proper/commons-io/javadocs/api-2.4/index.html
Use StringBuilder instead of String
then
StringBuilder test=new StringBuilder();
then in your while loop
test.append("your String");
Or you can use String as you wish as follows
String test=new String();
test +=your_String;
Try this
Scanner sc=new Scanner(new FileReader("D:\\Test.txt"));
StringBuilder test=new StringBuilder();
String str;
while (sc.hasNext()){
str=sc.next();
System.out.println(str);
test.append(str);
}
To read specific line
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Read {
public static void main(String[] args) throws IOException {
FileReader fr=new FileReader("D:\\Test.txt");
BufferedReader br=new BufferedReader(fr);
StringBuilder test=new StringBuilder();
String str;
int count=1;
while ((str=br.readLine())!=null){
if(count==1){
System.out.println(str);
test.append(str);
}
count++;
}
}
}

converting a string array to a double array

I am trying to convert a list of numbers from a txt file into an array of numbers. There is 26 numbers, and each is on a different line in the text file. My code is
import java.io.*;
public class rocket {
public static void main(String[] args) throws IOException, FileNotFoundException
{
BufferedReader b = new BufferedReader(new InputStreamReader(new FileInputStream("/Users/Jeremy/Documents/workspace/altitude.txt")));
String[] stringArray = new String[25];
double[] doubleArray = new double[stringArray.length];
for(int i=0; i<25; i++)
{
stringArray[i] = b.readLine();
doubleArray[i] = Double.parseDouble(stringArray[i]);
}
for(int i = 0; i<doubleArray.length; i++)
{
System.out.println(doubleArray[i]);
}
}
}
But every time I run it I get a number format exception. And if I try to just print out the strings I get an indexOutOfBounds exception
in question you have mentioned that there is 26 strings so declate
String[] stringArray = new String[26];
And The number format exception is occuring as readline returns with the linbreak. To read line you can do the following
public String[] readLines(String filename) throws IOException {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
bufferedReader.close();
return lines.toArray(new String[lines.size()]);
}
So by this logic you can get double by
public static Double[] readLines(String filename) throws IOException {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<Double> lines = new ArrayList<Double>();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(Double.parseDouble(line));
}
bufferedReader.close();
return lines.toArray(new Double[lines.size()]);
}
Try
BufferedReader b = new BufferedReader(
new InputStreamReader(
new FileInputStream(
"D:/git-repo/general/misc_test/src/java/com/greytip/cougar/module/test/v2/controller/so/dump/data.txt")));
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = b.readLine()) != null) {
lines.add(line);
}
String[] stringArray = lines.toArray(new String[lines.size()]);
double[] doubleArray = new double[stringArray.length];
for (int i = 0; i < stringArray.length; i++) {
doubleArray[i] = Double.parseDouble(stringArray[i]);
}
for (int i = 0; i < doubleArray.length; i++) {
System.out.println(doubleArray[i]);
}
String[] stringArray = new String[26];
try this
import java.io.*;
public class Rocket {
public static void main(String[] args) throws IOException, FileNotFoundException
{
BufferedReader b = new BufferedReader(new InputStreamReader(new FileInputStream("/Users/Jeremy/Documents/workspace/altitude.txt")));
String[] stringArray = new String[25];
double[] doubleArray = new double[stringArray.length];
for(int i=0; i<25; i++)
{
stringArray[i] = b.readLine();
try{
doubleArray[i] = Double.parseDouble(stringArray[i]);
}catch(Exception e)
{
e.printStackTrace();
}
}
for(int i = 0; i<doubleArray.length; i++)
{
System.out.println(doubleArray[i]);
}
}
}
Handle the Exception when parse a string to double please.

Categories

Resources