I have a text file, and when I read each line of the file and write it in array. I want to check if the character is not a dollar sign '$' . If it is, then Jump to next character and write the following part till the next dollar sign in next array. Therefore to divide each line in 3 parts, each part in different array.
Appreciate your time and help!
public void retrieveFromTxt() throws IOException
{
textArea.setText(" ");
String fileName = "Name_Of_City.txt";
String line = " ";
String entry = null;
y = 0;
char letter = '$', value = ' ';
FileReader fileReader = new FileReader(fileName);
BufferedReader br1 = new BufferedReader(fileReader);
String TextLine = br.readLine();
x = 1; // Random Variable to jump from character to character in array.
// To Get Values Back from FIle Each value in correct array, I seperated each value with "$" sign
// Checking each letter and printing it to array[y] possition until the $ sign is met, then jump over it and continue in other array.
try {
while(y < 19) {
while(TextLine != null) {
while(TextLine.charAt(x)!=(letter)) {
line = line + TextLine.charAt(x);
Country[y] = ( line );
x++;
}
}
while(TextLine != null) {
while(TextLine.charAt(x)!=(letter)) {
line = line + TextLine.charAt(x);
City[y] = ( line );
x++;
}
}
while((line = br1.readLine()) != null) {
while(line.charAt(x)!=(letter)) {
Population[y] = (textArea.getText()+ entry );
x++;
}
}
y++;
textArea.setText(textArea.getText()+ "\n" );
}
}
catch(FileNotFoundException error) {
//Exception can be met if program cannot find the file , in that case messageDialog will pop up with help message
JOptionPane.showMessageDialog(null,"Missing file"+", " + fileName + ", for a support contact oleninshelvijs#gmail.com!" ) ;
}catch (StringIndexOutOfBoundsException err){}
br1.close();
}
}
Try using the string.split function. You can do:
String s = "my$sign"
String parts[] = s.split("\\$")
Now parts[0] will hold "my" and parts[1] will hold "sign".
Edit: As pointed out by user Ukfub below, you will need to escape the symbol. Updating my code to reflect.
String parts[] = s.split("$")
That will not work because the parameter for the "split" method is a regular expression. You have to escape the special character '$':
String parts[] = s.split("\\$")
Related
I have a problem with some java code.
I'm returning a text from a method, which is on a .txt file. Then, I'm storing this text to a variable "text" and writing this on another .txt file. But the problem is: this new .txt file gets a new blank line at the bottom. That's because inside my method read, the variable "text" is receiving a "\n". How can I solve this problem?
PS: I'm doing this with educational purposes.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.FileReader;
import java.io.FileWriter;
public class Arquivo {
public static void main(String[] args) {
String text = read("in.txt");
write(text, "out.txt");
System.out.println("Text created!");
}
public static String read(String arquivo) {
String text = "";
try (BufferedReader br = new BufferedReader(new FileReader(arquivo))) {
String line = br.readLine();
while (line != null) {
text += line + "\n";
line = br.readLine();
}
} catch (IOException e) {
System.err.println(e.getMessage());
}
return text;
}
public static void write(String text, String arquivo) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(arquivo))) {
bw.write(text);
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
}
My two created files "in.txt" and "out.txt".
this is
a text file.
this is
a text file.
(blank line)
please try this:
String line = br.readLine();
while (line != null) {
text += line;
line = br.readLine();
if (line!=null){
text += "\n";
}
}
you can try this variant:
String line;
while((line = br.readLine()) != null) {
text += line;
if (line!=null){
text += "\n";
}
}
A good solution to this type of problem is to add the newline before you write each additional line:
String line = br.readLine();
text += line;
while ((line = br.readLine()) != null) {
text = "\n" + line;
}
This way, you only add the newline for each additional line you write (no extraneous ones at the end). Notice the assignment (plus null check) in the while loop).
replace write(text, "out.txt"); with
write(text.substring(0,text.length()-1), "out.txt");
which will remove the last character, which is the /n before writing.
Store all the strings in a list, then join on the line feed
public static void main( String[] args ) {
String text = read( "in.txt" );
write( text, "out.txt" );
System.out.println( "Text created!" );
}
public static String read( String arquivo ) {
List<String> texts = new ArrayList<>();
try ( BufferedReader br = new BufferedReader( new FileReader( arquivo ) ) ) {
String line = br.readLine();
while ( line != null ) {
texts.add( line );
line = br.readLine();
}
} catch ( IOException e ) {
System.err.println( e.getMessage() );
}
return texts.stream().collect( Collectors.joining( "\n" ) );
}
public static void write( String text, String arquivo ) {
try ( BufferedWriter bw = new BufferedWriter( new FileWriter( arquivo ) ) ) {
bw.write( text );
} catch ( IOException e ) {
System.err.println( e.getMessage() );
}
}
String.trim()
public String trim()
Returns a copy of the string, with leading and
trailing whitespace omitted. If this String object represents an empty
character sequence, or the first and last characters of character
sequence represented by this String object both have codes greater
than '\u0020' (the space character), then a reference to this String
object is returned.
Otherwise, if there is no character with a code greater than '\u0020'
in the string, then a new String object representing an empty string
is created and returned.
Otherwise, let k be the index of the first character in the string
whose code is greater than '\u0020', and let m be the index of the
last character in the string whose code is greater than '\u0020'. A
new String object is created, representing the substring of this
string that begins with the character at index k and ends with the
character at index m-that is, the result of this.substring(k, m+1).
This method may be used to trim whitespace (as defined above) from the
beginning and end of a string.
Returns: A copy of this string with leading and trailing white space
removed, or this string if it has no leading or trailing white space.
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#trim()
Simply trim the string before you return it from read.
public static String read(String arquivo) {
String text = "";
try (BufferedReader br = new BufferedReader(new FileReader(arquivo))) {
String line = br.readLine();
while (line != null) {
text += line + "\n";
line = br.readLine();
}
} catch (IOException e) {
System.err.println(e.getMessage());
}
return text.trim();
}
Just do not add \n before the last line:
String text = "";
...
String line = br.readLine();
boolean addNewLine = false;
while (line != null) {
if (addNewLine) {
text += "\n";
} else {
addNewLine = true;
}
text += line;
line = br.readLine();
}
Also, for performance improvement, consider using a StringBuilder instead of the string concatenation:
StringBuilder sb = new StringBuilder();
...
String line = br.readLine();
boolean addNewLine = false;
while (line != null) {
if (addNewLine) {
sb.append('\n');
} else {
addNewLine = true;
}
sb.append(line);
line = br.readLine();
}
...
String text = sb.toString();
I am trying to write a simple code that will give me the word count from a text file. The code is as follows:
import java.io.File; //to read file
import java.util.Scanner;
public class ReadTextFile {
public static void main(String[] args) throws Exception {
String filename = "textfile.txt";
File f = new File (filename);
Scanner scan = new Scanner(f);
int wordCnt = 1;
while(scan.hasNextLine()) {
String text = scan.nextLine();
for (int i = 0; i < text.length(); i++) {
if(text.charAt(i) == ' ' && text.charAt(i-1) != ' ') {
wordCnt++;
}
}
}
System.out.println("Word count is " + wordCnt);
}
}
this code compiles but does not give the correct word count. What am I doing incorrectly?
Right now you are only incrementing wordCnt if the character you are on is a whitespace and the character before it is not. However this discounts several cases, such as if there is not a space, but a newline character. Consider if your file looked like:
This is a text file\n
with a bunch of\n
words.
Your method should return ten, but since there is not space after the words file, and of it will not count them as words.
If you just want the word count you can do something along the lines of:
while(scan.hasNextLine()){
String text = scan.nextLine();
wordCnt+= text.split("\\s+").length;
}
Which will split on white space(s), and return how many tokens are in the resulting Array
First of all remember about closing resources. Please check this out.
Since Java 8 you can count words in this way:
String regex = "\\s+"
String filename = "textfile.txt";
File f = new File (filename);
long wordCnt = 1;
try (var scanner = new Scanner (f)){
wordCnt scanner.lines().map(str -> str.split(regex)).count();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Word count is " + wordCnt);
I was trying to search this complete word "(Error: 87)" in my text file.
I used below java code.
String path = "C:\\Temp\\Error_Hunter";
String fileName = "\\nvr-service.txt";
String testWord = "(Error: 87)";
int tLen = testWord.length();
int wordCntr = 0;
String file1 = path + fileName;
boolean check;
try{
FileInputStream fstream = new FileInputStream(file1);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while((strLine = br.readLine()) != null){
//check to see whether testWord occurs at least once in the line of text
check = strLine.toLowerCase().contains(testWord.toLowerCase());
if(check){
//get the line, and parse its words into a String array
String[] lineWords = strLine.split("\\s+");
for(String w : lineWords)
{
if(w.length() >= tLen){
String word = w.substring(0,tLen).trim();
if(word.equalsIgnoreCase(testWord))
{
wordCntr++;
}
}
}
}
}
System.out.println("total is: " + wordCntr);
//Close the input stream
br.close();
} catch(Exception e){
e.printStackTrace();
}
In my text file, the word has 104 hits. but this is not finding the word. because it contain space in between. Kindly suggest something or edit in the code itself.
Instead of
String[] lineWords = strLine.split("\\s+");
do
String[] tokens = strLine.split("(Error: 87)");
And then the number of occurrences of (Error: 87) in that line would be tokens.length - 1.
I want to calculate the number of lines of code within a program, and for which I had already written code which counts the number of ;. It works fine, but not in some situations like where there is no ; present (like if and while statements). In this case I had stored some of the keywords in an array of strings and I want to search for that keyword by using readLine(). If it works fine then I will increment it by 1, but it's not working. I had tried a lot but it is not working at all, and it is showing the Exception. As Demo.java you can use your own code.
Classdetect1.java
import java.io.*;
public class Classdetect1
{
public static void main(String[] args) throws IOException
{
int i=0,j=0,k=0,p;
String str1[]={"if","else","else if","while","for","goto","do"};
// Open the file
FileInputStream fstream = new FileInputStream("Demo.java");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
if (in == null){
System.out.println("File is blank");
System.exit(0);
}
while (i != -1)
{
i = in.read();
if(i==';' || i=='{')
{
j=j+1;
}
if(i=='\'')
{
while(in.read()!='\'')
continue;
}
if(i=='\"')
{
while(in.read()!='\"')
continue;
}
if(i=='(')
{
while(in.read()!=')')
continue;
}
while ((strLine = br.readLine()) != null)
{
for(p=0;p<7;p++)
{
if(str[p].equals(strLine))
{
k=k+1;
}
}
}
System.out.println("Line of =" + k);
}
System.out.println("Total Line of code=" + j);
}
}
In Java all statements end either with ; or with a block within { }. Some examples:
System.out.println("One statement");
while (str.equals("One block of statements + one statement"))
{
System.out.println("One statement");
}
Furthermore, the ; does not need to be on the same line at all:
System.out.println(
"One statement"
);
So you could simply count all ; (end of a statement) and all { (end of a statement, start of a block) and it will be fairly accurate.
if (true)
{ // One statement ending with '{'
doSomething(); // One statement ending with ';'
while (false)
{ // One statement ending with '{'
doSomethingElse(); // One statement ending with ';'
}
}
// 4 statements in total.
Of course, there are (as always) some exceptions:
if (true) doSomething(); // One statement, or two?
do { doSomething(); } while (true); // Three statements, or two?
Try this:
BufferedReader br = new BufferedReader(new FileReader(new File("C:/lines.txt")));
String s = "";
String text = "";
//save all the file in a string
while ((s = br.readLine()) != null) {
text += s + "\n";
}
//remove empty lines with a regex
String withoutEmptyLines = text.replaceAll("(?m)^[ \t]*\r?\n", "");
//lines of code = text with newline characters length - text without newline characters length
int linesOfCode = withoutEmptyLines.length() - withoutEmptyLines.replaceAll("\n", "").length();
System.out.println("Lines: "+linesOfCode);
My C:/lines.txt file:
01. a
02.
03. b
04. c
05. c
06. d
07. as
08. d
09. asd
10. asd
11. a
12.
13.
14.
15. asd
16.
17. asd
18.
19.
20.
21. asdasd
22.
23.
24.
With this file, the output is:
Lines: 13
Hope this helps
String line = "";
int lineNo;
try
{
File file = new File("/sdcard/mysdfile.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
//char[] inputBuffer1 = new char[READ_BLOCK_SIZE];
for (lineNo = 1; lineNo < 20; lineNo++)
{
if (lineNo == 1)
{
line = br.readLine();
etFName.setText(line);
}else//{br.readLine();}
if (lineNo == 2)
{
line = br.readLine();
char c = line.charAt(0);
//char c =line.charAt(0);
String s1 = Character.toString(c);
//String Str1 = line;
//String bloodgroup = String.copyValueOf(Str1, 10,13);
fBldGp.setText(s1);
}else//{br.readLine();}
if (lineNo == 5)
{
line = br.readLine();
char c = line.charAt(0);
String s1 = Character.toString(c);
etMName.setText(s1);
}else
if (lineNo == 6)
{
line = br.readLine();
char c = line.charAt(0);
String s1 = Character.toString(c);
mBldGp.setText(s1);
}else br.readLine();
}
}
catch (IOException e)
{
e.printStackTrace();
}
This gives me the required line but i am unable to get the specific word from that line
and add it to the textview in android layout. Please help me.
My expected output is to display the word of the line 1,2,5,6th line leaving first 10 alphabets of every line.
I'm not really sure what you're trying to accomplish, if you want a specific word you already know or whatever word is in a specific index value. But you can always check something like:
if(line.contains("word"){
fBldGp.setText("word");
}
But other than that then line.substring would give you a word starting at a specific index
This will give you list of all words(including space):
String[] words = line.split(" ");
You can access each word like this:
foreach(String word in words) {
System.out.println(word.trim()); // trim gets rid of the space from the beginning & end
}