I got an error: StringIndex out of range: -1 with error line is String anEmail = lineFromFile.substring(s+1, e). As you can see im trying to print a part of a line in an input file but i doesn't work. Can someone help me explain why?
import java.io.*;
public class Email13
{
static boolean isValidEmailCharacter(char c)
{
boolean result = false;
if((c>='A'&&c<='Z')||(c>='a'&&c<='z')||(c>='0'&&c<='9')||(c=='.')||(c=='-')||(c=='+'))
result = true;
return result;
}
public static void main(String[] args) throws Exception{
BufferedReader cin, fin;
cin = new BufferedReader(new InputStreamReader(System.in));
//Description
System.out.println("Programmer: Minh Nguyen");
System.out.println("Description: This program is to start the final project.");
System.out.println();
String nameIn, nameOut, deIn, deOut;
nameIn="";
nameOut="";
deIn = "fileContainingEmails.txt";
System.out.print("Enter input filename [default:" + deIn + "]: ");
nameIn = cin.readLine();
if(nameIn.compareTo("")==0){
nameIn = deIn;
deOut = "copyPasteMyEmails.txt";
System.out.print("Enter output filename [default:" + deOut + "]: ");
nameOut = cin.readLine();
if(nameOut.compareTo("")==0)
nameOut = deOut;
}
else if(nameIn.compareTo("")>0){
deOut = nameIn;
System.out.print("Enter output filename [default:" + deOut + "]: ");
nameOut = cin.readLine();
if(nameOut.compareTo("")==0)
nameOut = nameIn;
}
fin = new BufferedReader(new FileReader(nameIn));
//Read the input file
while(true)
{
if(!fin.ready()) break;
String lineFromFile;
lineFromFile = fin.readLine();
int s, e, hasDot;
for (int i = 0; i < lineFromFile.length(); i++) // for each char in the string...
{
if(lineFromFile.charAt(i)=='#')
{
for(s=i;s>-1;s--)
{
if(isValidEmailCharacter(lineFromFile.charAt(s))==false)
for(e=1; e< lineFromFile.length(); e++)
{
if(isValidEmailCharacter(lineFromFile.charAt(e))==false)
{
String anEmail = lineFromFile.substring(s+1, e);
System.out.println(anEmail);
break;
}
}
}
}
}
}
fin.close();
PrintWriter fout;
fout = new PrintWriter(new FileWriter(nameOut));
fout.close();
}
}
Suppose a line has 10 characters. So i loop goes from 0 to 9.
You then have a s loop, which goes from i to 0.
And inside that, you access `linefromFile.subString(s+1);
So when i is 9, your s loop starts at 9, and you try to access index 9+1, which is index 10, which is outside of your line.
Since Arrays are zero based indices, your lineFromFile.substring(s+1, e) is throwing an error.
for(s=i;s>-1;s--){
//lines of code
String anEmail = lineFromFile.substring(s+1, e)
This would fail for i = lineFromFile.length
as it would translate to lineFromFile[i+1] where lineFromFile[i] is the last element.
Related
I have a text file from which i am trying to search for a String which has multiple lines. A single string i am able to search but i need multi line string to be searched.
I have tried to search for single line which is working fine.
public static void main(String[] args) throws IOException
{
File f1=new File("D:\\Test\\test.txt");
String[] words=null;
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
String s;
String input="line one";
// here i want to search for multilines as single string like
// String input ="line one"+
// "line two";
int count=0;
while((s=br.readLine())!=null)
{
words=s.split("\n");
for (String word : words)
{
if (word.equals(input))
{
count++;
}
}
}
if(count!=0)
{
System.out.println("The given String "+input+ " is present for "+count+ " times ");
}
else
{
System.out.println("The given word is not present in the file");
}
fr.close();
}
And below are the file contents.
line one
line two
line three
line four
Use the StringBuilder for that, read every line from file and append them to StringBuilder with lineSeparator
StringBuilder lineInFile = new StringBuilder();
while((s=br.readLine()) != null){
lineInFile.append(s).append(System.lineSeparator());
}
Now check the searchString in lineInFile by using contains
StringBuilder searchString = new StringBuilder();
builder1.append("line one");
builder1.append(System.lineSeparator());
builder1.append("line two");
System.out.println(lineInFile.toString().contains(searchString));
More complicated solution from default C (code is based on code from book «The C programming language» )
final String searchFor = "Ich reiß der Puppe den Kopf ab\n" +
"Ja, ich reiß' ich der Puppe den Kopf ab";
int found = 0;
try {
String fileContent = new String(Files.readAllBytes(
new File("puppe-text").toPath()
));
int i, j, k;
for (i = 0; i < fileContent.length(); i++) {
for (k = i, j = 0; (fileContent.charAt(k++) == searchFor.charAt(j++)) && (j < searchFor.length());) {
// nothig
}
if (j == searchFor.length()) {
++found;
}
}
} catch (IOException ignore) {}
System.out.println(found);
Why don't you just normalize all the lines in the file to one string variable and then just count the number of occurrences of the input in the file. I have used Regex to count the occurrences but can be done in any custom way you find suitable.
public static void main(String[] args) throws IOException
{
File f1=new File("test.txt");
String[] words=null;
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
String s;
String input="line one line two";
// here i want to search for multilines as single string like
// String input ="line one"+
// "line two";
int count=0;
String fileStr = "";
while((s=br.readLine())!=null)
{
// Normalizing the whole file to be stored in one single variable
fileStr += s + " ";
}
// Now count the occurences
Pattern p = Pattern.compile(input);
Matcher m = p.matcher(fileStr);
while (m.find()) {
count++;
}
System.out.println(count);
fr.close();
}
Use StringBuilder class for efficient string concatenation.
Try with Scanner.findWithinHorizon()
String pathToFile = "/home/user/lines.txt";
String s1 = "line two";
String s2 = "line three";
String pattern = String.join(System.lineSeparator(), s1, s2);
int count = 0;
try (Scanner scanner = new Scanner(new FileInputStream(pathToFile))) {
while (scanner.hasNext()) {
String withinHorizon = scanner.findWithinHorizon(pattern, pattern.length());
if (withinHorizon != null) {
count++;
} else {
scanner.nextLine();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println(count);
Try This,
public static void main(String[] args) throws IOException {
File f1 = new File("./src/test/test.txt");
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
String input = "line one";
int count = 0;
String line;
while ((line = br.readLine()) != null) {
if (line.contains(input)) {
count++;
}
}
if (count != 0) {
System.out.println("The given String " + input + " is present for " + count + " times ");
} else {
System.out.println("The given word is not present in the file");
}
fr.close();
}
I need the below code to move to next line and not to restart from first line again
public void actionPerformed(ActionEvent e) {
String getTextArea;
getTextArea = textArea.getText();
String[] arr = getTextArea.split("\\n");
String type = null;
String serial = null;
try {
for(String s : arr) {
if(s.isEmpty()) {
textArea_1.append("Empty line" + '\n');
s = getTextArea;
}
type = s.substring(0, 4);
serial = s.substring(5, 12);
URL url = new URL("blablabla" + type + serial);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String result;
Scanner sc;
sc = new Scanner(in);
while(sc.hasNext()) {
result = sc.next();
if (result.contains("Type:")) {
result = sc.nextLine();
result = sc.nextLine();
result = result.substring(26,30);
textArea_1.append(result + '\t');
}
result = sc.nextLine();
result = sc.nextLine();
result = result.substring(26, 29);
textArea_1.append(result + '\t');
}
}
}
} catch (Exception e2) {
// TODO: handle exception
}
}
});
Here is a picture to show the result
As you see after writing empty line the first line is repeated again !
I think that instead of s = getTextArea; in the if block, you should have continue; to advance to the next element in arr.
I am have a project that need to modify some text in the text file.
Like BB,BO,BR,BZ,CL,VE-BR
I need make it become BB,BO,BZ,CL,VE.
and HU, LT, LV, UA, PT-PT/AR become HU, LT, LV, UA,/AR.
I have tried to type some code, however the code fail to loop and also,in this case.
IN/CI, GH, KE, NA, NG, SH, ZW /EE, HU, LT, LV, UA,/AR, BB
"AR, BB,BO,BR,BZ,CL, CO, CR, CW, DM, DO,VE-AR-BR-MX"
I want to delete the AR in second row, but it just delete the AR in first row.
I got no idea and seeking for helps.
Please
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.Scanner;
public class tomy {
static StringBuffer stringBufferOfData = new StringBuffer();
static StringBuffer stringBufferOfData1 = stringBufferOfData;
static String filename = null;
static String input = null;
static String s = "-";
static Scanner sc = new Scanner(s);
public static void main(String[] args) {
boolean fileRead = readFile();
if (fileRead) {
replacement();
writeToFile();
}
System.exit(0);
}
private static boolean readFile() {
System.out.println("Please enter your files name and path i.e C:\\test.txt: ");
filename = "C:\\test.txt";
Scanner fileToRead = null;
try {
fileToRead = new Scanner(new File(filename));
for (String line; fileToRead.hasNextLine()
&& (line = fileToRead.nextLine()) != null;) {
System.out.println(line);
stringBufferOfData.append(line).append("\r\n");
}
fileToRead.close();
return true;
} catch (FileNotFoundException ex) {
System.out.println("The file " + filename + " could not be found! "+ ex.getMessage());
return false;
} finally {
fileToRead.close();
return true;
}
}
private static void writeToFile() {
try {
BufferedWriter bufwriter = new BufferedWriter(new FileWriter(
filename));
bufwriter.write(stringBufferOfData.toString());
bufwriter.close();
} catch (Exception e) {// if an exception occurs
System.out.println("Error occured while attempting to write to file: "+ e.getMessage());
}
}
private static void replacement() {
System.out.println("Please enter the contents of a line you would like to edit: ");
String lineToEdit = sc.nextLine();
int startIndex = stringBufferOfData.indexOf(lineToEdit);
int endIndex = startIndex + lineToEdit.length() + 2;
String getdata = stringBufferOfData.substring(startIndex + 1, endIndex);
String data = " ";
Scanner sc1 = new Scanner(getdata);
Scanner sc2 = new Scanner(data);
String lineToEdit1 = sc1.nextLine();
String replacementText1 = sc2.nextLine();
int startIndex1 = stringBufferOfData.indexOf(lineToEdit1);
int endIndex1 = startIndex1 + lineToEdit1.length() + 3;
boolean test = lineToEdit.contains(getdata);
boolean testh = lineToEdit.contains("-");
System.out.println(startIndex);
if (testh = true) {
stringBufferOfData.replace(startIndex, endIndex, replacementText1);
stringBufferOfData.replace(startIndex1, endIndex1 - 2,
replacementText1);
System.out.println("Here is the new edited text:\n"
+ stringBufferOfData);
} else {
System.out.println("nth" + stringBufferOfData);
System.out.println(getdata);
}
}
}
I wrote a quick method for you that I think does what you want, i.e. remove all occurrences of a token in a line, where that token is embedded in the line and is identified by a leading dash.
The method reads the file and writes it straight out to a file after editing for the token. This would allow you to process a huge file without worrying about about memory constraints.
You can simply rename the output file after a successful edit. I'll leave it up to you to work that out.
If you feel you really must use string buffers to do in memory management, then grab the logic for the line editing from my method and modify it to work with string buffers.
static void onePassReadEditWrite(final String inputFilePath, final String outputPath)
{
// the input file
Scanner inputScanner = null;
// output file
FileWriter outputWriter = null;
try
{
// open the input file
inputScanner = new Scanner(new File(inputFilePath));
// open output file
File outputFile = new File(outputPath);
outputFile.createNewFile();
outputWriter = new FileWriter(outputFile);
try
{
for (
String lineToEdit = inputScanner.nextLine();
/*
* NOTE: when this loop attempts to read beyond EOF it will throw the
* java.util.NoSuchElementException exception which is caught in the
* containing try/catch block.
*
* As such there is NO predicate required for this loop.
*/;
lineToEdit = inputScanner.nextLine()
)
// scan all lines from input file
{
System.out.println("START LINE [" + lineToEdit + "]");
// get position of dash in line
int dashInLinePosition = lineToEdit.indexOf('-');
while (dashInLinePosition != -1)
// this line has needs editing
{
// split line on dash
String halfLeft = lineToEdit.substring(0, dashInLinePosition);
String halfRight = lineToEdit.substring(dashInLinePosition + 1);
// get token after dash that is to be removed from whole line
String tokenToRemove = halfRight.substring(0, 2);
// reconstruct line from the 2 halves without the dash
StringBuilder sb = new StringBuilder(halfLeft);
sb.append(halfRight.substring(0));
lineToEdit = sb.toString();
// get position of first token in line
int tokenInLinePosition = lineToEdit.indexOf(tokenToRemove);
while (tokenInLinePosition != -1)
// do for all tokens in line
{
// split line around token to be removed
String partLeft = lineToEdit.substring(0, tokenInLinePosition);
String partRight = lineToEdit.substring(tokenInLinePosition + tokenToRemove.length());
if ((!partRight.isEmpty()) && (partRight.charAt(0) == ','))
// remove prefix comma from right part
{
partRight = partRight.substring(1);
}
// reconstruct line from the left and right parts
sb.setLength(0);
sb = new StringBuilder(partLeft);
sb.append(partRight);
lineToEdit = sb.toString();
// find next token to be removed from line
tokenInLinePosition = lineToEdit.indexOf(tokenToRemove);
}
// handle additional dashes in line
dashInLinePosition = lineToEdit.indexOf('-');
}
System.out.println("FINAL LINE [" + lineToEdit + "]");
// write line to output file
outputWriter.write(lineToEdit);
outputWriter.write("\r\n");
}
}
catch (java.util.NoSuchElementException e)
// end of scan
{
}
finally
// housekeeping
{
outputWriter.close();
inputScanner.close();
}
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
catch(IOException e)
{
inputScanner.close();
e.printStackTrace();
}
}
I'm trying to count the number of Words, Lines and characters(excluding whitespace). The only part I can't get to work is ignoring the whitespace for the character count.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Exercise2 {
public static void main(String[] args) throws IOException{
File file = getValidFile();
int count = wordCount(file);
int lines = lineCount(file);
int characters = characterCount(file);
System.out.println("Total Words = " + count);
System.out.println("Total Lines = " + lines);
System.out.println("Total Characters = " + characters);
}
public static int characterCount(File file) throws IOException {
{
Scanner inputFile = new Scanner(file).useDelimiter(",\\s*");;
int characters = 0; // initialise the counter variable
while (inputFile.hasNext())
{
inputFile.next(); //read in a word
characters++; //count the word
}
inputFile.close();
return characters;
}
}
public static int lineCount(File file)throws IOException {
{
Scanner inputFile = new Scanner(file);
int lines = 0; // initialise the counter variable
while (inputFile.hasNext())
{
inputFile.nextLine(); //read in a line
lines++; //count the line
}
inputFile.close();
return lines;
}
}
public static int wordCount(File file) throws IOException {
{
Scanner inputFile = new Scanner(file);
int count = 0; // initialise the counter variable
while (inputFile.hasNext())
{
inputFile.next(); //read in a word
count++; //count the word
}
inputFile.close();
return count;
}
}
public static File getValidFile()
{
String filename; // The name of the file
File file;
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Get a valid file name.
do
{
/*for (int i = 0; i < 2; i ++ )
{*/
System.out.print("Enter the name of a file: ");
filename = keyboard.nextLine();
file = new File(filename);
if (!file.exists())
System.out.println("The specifed file does not exist - please try again!");
}while( !file.exists());
return file;
}
}
If you want to count the characters in the file, excluding any whitespace, you can read your file line by line and accumulate the character count, or read the whole file in a String and do the character count, e.g.
String content = new Scanner(file).useDelimiter("\\Z").next();
int count = 0;
for (int i = 0; i < content.length(); i++) {
if (!Character.isWhitespace(content.charAt(i))) {
count++;
}
}
System.out.println(count);
EDIT
Other solutions if you don't care about the content of the file, then there is no need to load it into a String, you can just read character by character.
Example counting the non-whitespace characters in Arthur Rimbaud poetry.
Using a Scanner
URL rimbaud = new URL("http://www.gutenberg.org/cache/epub/29302/pg29302.txt");
int count = 0;
try (BufferedReader in = new BufferedReader(new InputStreamReader(rimbaud.openStream()))) {
int c;
while ((c = in.read()) != -1) {
if (!Character.isWhitespace(c)) {
count++;
}
}
}
System.out.println(count);
Using a plain StreamReader
count = 0;
try (Scanner sin = new Scanner(new BufferedReader(new InputStreamReader(rimbaud.openStream())))) {
sin.useDelimiter("");
char c;
while (sin.hasNext()) {
c = sin.next().charAt(0);
if (!Character.isWhitespace(c)) {
count++;
}
}
}
System.out.println(count);
I have a line of text that I need to decrypt into a cipher text.
Let's say my line of text is abc def ghijklm n opq rstu vwx yz
and I want an output like this: aei qu c k rvzdhmptxbfjn y glosm
lets say I entered my "key" as 5. The code then will enter every 5th element of the array o f strings of the text from the text file.
This is the code I have come up with and I have hit a wall on what to do.
import java.io.*;
import java.util.*;
public class Files1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int key;
System.out.print("Enter file: ");
String fileName = input.nextLine();
System.out.print("Please enter your Cipher Key: ");
key = input.nextInt();
Scanner inputStream = null;
System.out.println("File name is: " + fileName);
try {
inputStream = new Scanner(new File(fileName));
} catch (FileNotFoundException e) {
System.out.println("Error opening the file" + fileName);
System.exit(0);
}
while (inputStream.hasNextLine()) {
String text = inputStream.nextLine();
System.out.println(text);
char arrayText[] = text.toCharArray();
for (int i = 0; i < arrayText.length; i += key) {
System.out.print("\n" + arrayText[i]);
}
}
}
}
Here is whats happening in the console:
Enter file: abc.txt
File name is: abc.txt
abc def ghijklm n opq rstu vwx yz
a
e
i
q
u
What you need is a circular list.
Here is a very simple and crude implementation of a circular list using arrays.
import java.util.Iterator;
import java.util.List;
public class CircularList implements Iterator<String> {
private String[] list;
private int pointerIndex;
private int key;
public CircularList(String[] list, int key) {
this.list = list;
pointerIndex = 1 - key;
this.key = key;
}
#Override
public boolean hasNext() {
if(list.length == 0){
return false;
}
return true;
}
#Override
public String next() {
if(pointerIndex + key > list.length) {
int diff = (list.length-1) - pointerIndex;
pointerIndex = key - diff;
return list[pointerIndex];
}else {
pointerIndex = pointerIndex + key;
return list[pointerIndex];
}
}
#Override
public void remove() {
//Do Nothing
}
}
Once you have a list in which you can iterate in a circular fashion, you can change you existing implementation to this -
import java.io.*;
import java.util.*;
public class Files1 {
public static void main(String[] args) {
System.out.print("Enter file: ");
Scanner input = new Scanner(System.in);
String fileName = input.nextLine();
Scanner inputStream = null;
System.out.println("" + fileName);
try {
inputStream = new Scanner(new File(fileName));
} catch (FileNotFoundException e) {
System.out.println("Error opening the file: " + fileName);
System.exit(0);
}
while (inputStream.hasNextLine()) {
String text = inputStream.nextLine();
System.out.println(text);
String[] splits = text.split("");
CircularList clist = new CircularList(splits, 5);
for (int i = 0; i < splits.length -1; i += 1) {
System.out.print("" + clist.next());
}
}
}
}
Output -
Enter file: resources\abc.txt
resources\abc.txt
abc def ghijklm n opq rstu vwx yz
aei qu c k rvzdhmptxbfjn y glosw
Also the last character in your cipher should be 'w' and not 'm'.
You don't specify what should happen to the spaces, or what happens when wraparound is required, but assuming spaces are significant and wrap-around just happens naturally:
for (int i = 0; i < text.length(); i++)
{
System.out.print(text.charAt((i*5) % text.length()));
}
prints aei qu c k rvzdhmptxbfjn y glosw, which strongly suggests an error in your expected output.
import java.io.;
import java.util.;
public class Files1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int key;
System.out.print("Enter file: ");
String fileName = input.nextLine();
System.out.print("Please enter your Cipher Key: ");
key = input.nextInt();
Scanner inputStream = null;
System.out.println("File name is: " + fileName);
try {
inputStream = new Scanner(new File(fileName));
} catch (FileNotFoundException e) {
System.out.println("Error opening the file" + fileName);
System.exit(0);
}
while (inputStream.hasNextLine()) {
String text = inputStream.nextLine();
System.out.println(text);
for (int i = 0; i < text.length(); i++) {
System.out.print(text.charAt((i * key) % text.length()));
}
}
}
}
MANY THANKS TO EJP AND Pai!
i learned alot!