Error while reading file? - java

I am working on a project for java and I want the comiler to differentiate between number and words, but when I try the code as is, it returns error due to string of -1. Also, how do I make the number I am reading in into * symbols in a graph? Any help would be greatly appreciated
Orville’s Acres, 114.8 43801
Hoffman’s Hills, 77.2 36229
Jiffy Quick Farm, 89.4 24812
Jolly Good Plantation, 183.2 104570
Organically Grown Inc., 45.5 14683
(What I am reading in)
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.*;
import java.io.*;
public class Popcorn {
public static void main (String [] args) throws IOException {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
String filename = f.getName();
Scanner infile = new Scanner(new FileReader( filename));
String line = "" ;
while (infile.hasNextLine())
{ line= infile.nextLine();
// int endingIndex =line.indexOf(',');
//String fromName = line.substring(0, endingIndex);
System.out.println(line);}
infile.close();
}
}

Use Integer.parseInt() to know if its a number. Have a catch exception block and if it comes in catch block, you'd know its not a number

Related

Java- Making a File from template with layout?

What I'm trying to achieve is a program that makes a file from the template called WaarschuwingsBriefTemplate.txt (WarningLetterTemplate).The method is called with a Klant (Customer) in its parantheses.
Now when I call this method, it won't write any enters at all, even though there are enters in the Template and I'm trying to add enters in the method itself but it doesnt seem to work. Brief translation of the foreign words:
NAAM = NAME
ADRES = ADDRESS
POSTCODE = ZIP CODE
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FileMaker {
public FileMaker(){
}
public void maakWaarschuwingsBrief(Klant k) throws IOException{
File file = new File("WaarschuwingsBriefTemplate.txt");
String newFile = "";
try{
Scanner sc = new Scanner(file);
while(sc.hasNextLine()){
String line = sc.nextLine();
if(line.contains("--NAAM--")){
line = line.replace("--NAAM--", k.getNaam())+"\n";
}
if(line.contains("--ADRES--")){
line = line.replace("--ADRES--", k.getAdres())+"\n";
}
if(line.contains("--POSTCODE--")){
line = line.replace("--POSTCODE--", k.getPostcode())+"\n";
}
newFile += line + "\n";
}
sc.close();
}catch(FileNotFoundException e){
e.printStackTrace();
}
File file2 = new File(k.getNaam().replaceAll("\\s","")+".txt");
if(!file2.exists()){
file2.createNewFile();
}
FileWriter fw = new FileWriter(file2.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(newFile);
bw.close();
}
}
`
If your template is not too big and it's ok to read the file as whole to memory maybe try https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/text/StrSubstitutor.html instead of manual manipulation?
Also use http://docs.oracle.com/javase/8/docs/api/java/lang/System.html#lineSeparator-- instead of "\n"

Scanner only works with one out of multiple classes Java

I have a program with the purpose of analyzing a text file that the user selects via typing in the full path of the text file when prompted.
I have managed to get the scanner into multiple classes however it will not work for each method simultaneously. For example I have a class that will print the amount of numbers in the file and another that will print the number of words in the file. However only the first method that is run will work, the other will display 0 of whatever the class is searching for(numbers, lines, words etc) even if the true value is not actually 0.
I'm really stuck with why this is happening, I have attached the main class with two other classes to show a clear example:
Main Class:
package cw;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JFileChooser;
import java.io.IOException;
public class TextAnalyser {
public static Scanner reader;
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
System.out.println("Enter a filename");
String filename = in.nextLine();
File InputFile = new File (filename);
reader = new Scanner (InputFile);
LineCounter Lineobject = new LineCounter();
WordCounter Wordobject = new WordCounter();
Lineobject.TotalLines();
Wordobject.TotalWords();
}
}
Class that counts lines:
package cw;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JFileChooser;
import java.io.IOException;
public class LineCounter {
public static void TotalLines() throws IOException {
// Scanner sc = new Scanner(TextAnalyser.class.getResourceAsStream("test.txt"));
Scanner sc = TextAnalyser.reader;
PrintWriter out = new PrintWriter(new FileWriter("C:\\Users\\Sam\\Desktop\\Report.txt", true));
int linetotal = 0;
while (sc.hasNextLine()) {
sc.nextLine();
linetotal++;
}
out.println("The total number of lines in the file = " + linetotal);
out.flush();
out.close();
System.out.println("The total number of lines in the file = " + linetotal);
}
}
Class that Counts words:
package cw;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JFileChooser;
import java.io.IOException;
public class WordCounter {
public static Scanner sc = TextAnalyser.reader;
public static void TotalWords() throws IOException{
//Scanner sc = new Scanner(TextAnalyser.class.getResourceAsStream("test.txt"));
PrintWriter out = new PrintWriter(new FileWriter("C:\\Users\\Sam\\Desktop\\Report.txt", true));
int wordtotal = 0;
while (sc.hasNext()){
sc.next();
wordtotal++;
}
out.println("The total number of words in the file = " + wordtotal);
out.flush();
out.close();
System.out.println("The total number of words in the file = " + wordtotal);
}
}
For some reason only one will work at a time, one will always say there are 0, if someone could explain to me why this is happening and how to solve it, it would really help, Thanks!
reader = new Scanner (InputFile); contains a reference to the Scanner object, when you use public static Scanner sc = TextAnalyser.reader; in both methods you are copying the reference of reader into sc, so all of them are the same object. Why having 2 variables referencing all the same object one of which is redefined two times with the same value?
The problem here is that the scanner reaches the end of the file and when you call it again (it is the same object) it has nothing more to read, so you should create another scanner object (maybe it is what you was attempting to do?). A better solution would be to read the file once and store the contents in some data structure.

read input from txt file names(one word) and (ints). write to output file the lists with ages then names

When finished output should be:
15 Michael
16 Jessica
20 Christopher
19 Ashley
etc.
I am not that good at this and would like any input whatsoever on how to get the int and strings to print line by line. I have avoided an array approach because I always have difficulty with arrays. Can anyone tell me if I am on the right track and how to properly parse or type cast the ints so they can be printed on a line to the output file? I have been working for days on this and any help would be much appreciated! Here is what I have so far.
import java.io.PrintWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class NameAgeReverse
{
public static void main (String[] args)
{
System.out.println("Programmed by J");
String InputFileName;
String OutputFileName;
Scanner keyboard = new Scanner(System.in);
System.out.print("Input file: ");
InputFileName = keyboard.nextLine();
System.out.print("Output file: ");
OutputFileName = keyboard.nextLine();
Scanner inputStream = null;
PrintWriter outputStream = null;
try
{
inputStream = new Scanner(new FileInputStream("nameAge.txt"));
outputStream =new PrintWriter(new FileOutputStream("ageName.txt"));
}
catch(FileNotFoundException e)
{
System.out.println("File nameAge.txt was not found");
System.out.println("or could not be opened.");
System.exit(0);
}
int x = 0;
String text = null;
String line = null;
while(inputStream.hasNextLine())
{
text = inputStream.nextLine();
x = Integer.parseInt(text);
outputStream.println(x + "\t" + text);
}
inputStream.close();
outputStream.close();
}
}
Here are my error messages:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Michael"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at NameAgeReverse.main(NameAgeReverse.java:52)
text = inputStream.nextLine(); will read the whole line of text with both name and age. Assuming the format of every line in your input file is age name, you can do the following parse every line of text into desirable values. Note that this won't work out of the box with the rest of your code. Just a pointer:
text = inputStream.nextLine().split(" "); // split each line on space
age = Integer.parseInt(text[0]); // age is the first string
name = text[1];
This should work:
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class ReadWriteTextFile {
final static Charset ENCODING = StandardCharsets.UTF_8;
public static void main(String... aArgs) throws IOException{
List<String> inlines = Files.readAllLines(Paths.get("/tmp/nameAge.txt"), ENCODING);
List<String> outlines = new ArrayList<String>();
for(String line : inlines){
String[] result = line.split("[ ]+");
outlines.add(result[1]+" "+result[0]);
}
Files.write(Paths.get("/tmp/ageName.txt"), outlines, ENCODING);
}
}

Separating texts from a File with String.Split nothing happens

EDITED
Im trying to split a text into an Array. I have a .txt made by different text, like a collection of texts. I need the whole text of each different text in the .txt in a position of the Array.
Im recovering the text from the file with a JFileChooser. And then im trying to process it with "regex" String.Split and then trying to print it. "The first part of the FileChooser it works, but when trying to separate the text in the Array i dont know if its working, because the System.out does not print the expected Array whit all the texts."
This is an example of the .txt each text is separated by a "*TEXT".
*TEXT 017 01/04/63 PAGE 020
THE ALLIES AFTER NASSAU IN DECEMBER 1960, THE U.S ........
*TEXT 020 01/04/63 PAGE 021
THE ROAD TO JAIL IS PAVED WITH NONOBJECTIVE ART SINCE THE KREMLIN'S SHARPEST BARBS THESE DAYS ARE AIMED AT MODERN ART AND WESTERN ESPIONAGE...
*TEXT 025 01/04/63 PAGE 024
RED CHINA FIXING FRONTIERS RED CHINA PRODUCED A SECOND SURPRISE LAST WEEK...
An this is my code, first the FileChooser and then the String.Split
import java.io.*;
import java.lang.Object.*;
import java.util.regex.*;
import javax.swing.JFileChooser;
public class Reader{
public static void main(String args[]) throws IOException{
File inFile;
FileReader fr;
BufferedReader bufReader;
JFileChooser chooser;
int reply;
String doc = "";
String line;
try{
chooser = new JFileChooser();
reply = chooser.showOpenDialog(null);
doc = chooser.getCurrentDirectory().getPath() + System.getProperty("file.separator") + chooser.getSelectedFile().getName();
inFile = new File(doc);
fr = new FileReader(inFile);
bufReader = new BufferedReader (fr);
do{
line = bufReader.readLine();
if(line ==null )
return;
} while(line!=null);
//**HERE STARTS THE STRING.SPLIT**
//"line" at the end of next line it supposed to be the whole .txt
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(line)));
StringBuilder br = new StringBuilder();
String newLine ="";
while(true){
if(line == null)
break;
br.append(line);
}
newLine = br.toString();
String arr[] = newLine.split("\\*TEXT");
System.out.println(java.util.Arrays.toString(arr));
//**HERE ENDS**
bufReader.close();
}//end try
catch(Exception e)
{ System.out.println("error: "+e.getMessage()); }
}//main
}//end class reader
Thanks for your help! :3
First and foremost, your code never reaches the call to split. Your code has only two paths: the user cancels the file chooser dialog, which causes a NullPointerException, or a file is chosen, which inevitably hits the return statement in
...
do{
line = bufReader.readLine();
if(line ==null )
return;
} while(line!=null);
Second, the line
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(line)));
tries to open the file with name specified by the value of variable line which is probably not what you want.
A fixed version of your code would be:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import javax.swing.JFileChooser;
public class Reader{
public static void main(String args[]) throws IOException{
File inFile;
FileReader fr;
BufferedReader bufReader;
JFileChooser chooser;
int reply;
try{
chooser = new JFileChooser();
reply = chooser.showOpenDialog(null);
// Read all the lines in the file at once
List<String> lines = Files.readAllLines(Paths.get(chooser.getSelectedFile().getAbsolutePath()), StandardCharsets.UTF_8);
// Merge the read lines into a String
StringBuilder sb = new StringBuilder();
for (String line : lines){
sb.append(line);
sb.append('\n');
}
String newLine = sb.toString();
// Split the String
String arr[] = newLine.split("\\*TEXT");
System.out.println(java.util.Arrays.toString(arr));
}//end try
catch(Exception e)
{ System.out.println("error: "+e.getMessage()); }
}//main
}//end class reader
Note the API classes Files and Paths are available starting Java API 1.7 only.
You can split the text using this regex:
^(?=\*TEXT)
Working demo

why is Scanner's hasNext() method initially returning false for a non-empty text file?

I'm trying to write some text to a file. I have a while loop that is supposed to just take some text and write the exact same text back to the file.
I discovered that the while loop is never entered because Scanner thinks there's no more text to read. But there is.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class WriteToFile {
public static void main(String[] args) throws FileNotFoundException {
String whatToWrite = "";
File theFile = new File("C:\\test.txt");
Scanner readinput = new Scanner(theFile);
PrintWriter output = new PrintWriter(theFile);
while (readinput.hasNext()) { //why is this false initially?
String whatToRead = readinput.next();
whatToWrite = whatToRead;
output.print(whatToWrite);
}
readinput.close();
output.close();
}
}
The text file just contains random words. Dog, cat, etc.
When I run the code, text.txt becomes empty.
There was a similar question: https://stackoverflow.com/questions/8495850/scanner-hasnext-returns-false which pointed to encoding issues. I use Windows 7 and U.S. language. Can I find out how the text file is encoded somehow?
Update:
Indeed, as Ph.Voronov commented, the PrintWriter line erases the file contents! user2115021 is right, if you use PrintWriter you should not work on one file. Unfortunately, for the assignment I had to solve, I had to work with a single file. Here's what I did:
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class WriteToFile {
public static void main(String[] args) throws FileNotFoundException {
ArrayList<String> theWords = new ArrayList<String>();
File theFile = new File("C:\\test.txt");
Scanner readinput = new Scanner(theFile);
while (readinput.hasNext()) {
theWords.add(readinput.next());
}
readinput.close();
PrintWriter output = new PrintWriter(theFile); //we already got all of
//the file content, so it's safe to erase it now
for (int a = 0; a < theWords.size(); a++) {
output.print(theWords.get(a));
if (a != theWords.size() - 1) {
output.print(" ");
}
}
output.close();
}
}
PrintWriter output = new PrintWriter(theFile);
It erases your file.
You are trying to read the file using SCANNER and writing to another file using PRINTWRITER,but both are working on same file.PRINTWRITER clear the content of the file to write the content.Both the class need to work on different file.

Categories

Resources