My aim is to read the first element/term of each line from a given input file and then decide what to do (using an if-else construct) depending on what that first element is. I.e. if the first element/word happens to be "the" (as mentioned in the code below), then I have to skip that line and move to the next line.
I have written the following code till now but I am not sure on how to read only the first element of each line of the text file that I am passing as input.
public static void main(String[] args) {
BufferedReader br = null;
try {
String line;
br = new BufferedReader(new FileReader("input.txt"));
while ((line = br.readLine()) != null) {
System.out.println(line);
StringTokenizer stringTokenizer = new StringTokenizer(line, " ");
while (stringTokenizer.hasMoreTokens()) {
String term = stringTokenizer.nextElement().toString();
if (term.equals("the")) {
//Code on what to do depending on the first character of each line.
}
StringBuilder sb = new StringBuilder();
System.out.println(sb.toString());
}
}
System.out.println("Done!");
}
catch (IOException e)
{
e.printStackTrace();
}
finally {
try {
if (br != null)
br.close();
}
catch(IOException ex) {
ex.printStackTrace();
}
}
}
Below is the simple code that prints the as the output. you can use this and no need to create an extra array or use StringTokenizer.
String s = "The a an the abcdef.";
System.out.println(s.contains(" ") ? s.substring(0, s.indexOf(" ")) : s);
You can turn each term into an array of words via:
while((line = br.readLine()) != null){
System.out.println(line);
String word = line.split("\\s+")[0];
if(word.equals("the")){
//Code on what to do depending on the first character of each line.
}
StringBuilder sb = new StringBuilder();
System.out.println(sb.toString());
}
...
but I am not sure on how to read only the first element of each line of the text file that I am passing as input.
There are a couple of different solutions depending on your exact requirement.
You can read the entire line of data and then use the String.startsWith(...) method to test for the first word. Using this approach you don't tokenize all the data if you just want to skip the rest of the line. Then if you want to continue processing you can use the String.substring(...) method to get the rest of the data from the line.
You can use the Scanner class. The Scanner allows you to tokenize the input as you read the data from the file. So you can read the first word and then determine whether to skip the rest of the data or read the rest of the line.
StringTokenizer is considered as legacy class. It is only there for backward compatibility. Use split() on string to split the single string into array of strings/words.
String[] s = line.readLine().split(" ");
String firstWord = s[0]; // ->First word
So your code can be edited to
public static void main(String[] args)
{
BufferedReader br = null;
try
{
String line;
br = new BufferedReader(new FileReader("input.txt"));
while((line = br.readLine()) != null)
{
System.out.println(line);
String s = line.split(" "); // instead of StringTokenizer
if(s[0].equals("the"))
{
//Code on what to do depending on the first character of each line.
}
StringBuilder sb = new StringBuilder();
System.out.println(sb.toString());
}
System.out.println("Done!");
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (br != null)
br.close();
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
}
Note:
Don't use startsWith(...) to check for the first word because it checks by character-wise instead of word-wise. If you want to check for the word the then the words there,their also returns true which might break your code.
Try to use split() instead of StringTokenizer from now onwards.
Related
I tried concatenating 2 lines of text in a given text file and printing the output to the console. My code is very complicated, is there a simpler method to achieve this by using FileHandling basic concepts ?
import java.io.*;
public class ConcatText{
public static void main(String[] args){
BufferedReader br = null;
try{
String currentLine;
br = new BufferedReader(new FileReader("C:\\Users\\123\\Documents\\CS105\\FileHandling\\concat.file.text"));
StringBuffer text1 = new StringBuffer (br.readLine());
StringBuffer text2 = new StringBuffer(br.readLine());
text1.append(text2);
String str = text1.toString();
str = str.trim();
String array[] = str.split(" ");
StringBuffer result = new StringBuffer();
for(int i=0; i<array.length; i++) {
result.append(array[i]);
}
System.out.println(result);
}
catch(IOException e){
e.printStackTrace();
}finally{
try{
if(br != null){
br.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
}
The text file is as follows :
GTAGCTAGCTAGC
AGCCACGTA
the output should be as follows (concatenation of the text file Strings) :
GTAGCTAGCTAGCAGCCACGTA
If you are using java 8 or newer, the simplest way would be:
List<String> lines = Files.readAllLines(Paths.get(filePath));
String result = String.join("", lines);
If you are using java 7, at least you can use try with resources to reduce the clutter in the code, like this:
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
StringBuffer text1 = new StringBuffer (br.readLine());
StringBuffer text2 = new StringBuffer(br.readLine());
// ...
}catch(IOException e){
e.printStackTrace();
}
This way, resources will be autoclosed and you don't need to call br.close().
Short answer, there is:
public static void main(String[] args) {
//this is called try-with-resources, it handles closing the resources for you
try (BufferedReader reader = new BufferedReader(...)) {
StringBuilder stringBuilder = new StringBuilder();
String line = reader.readLine();
//readLine() will return null when there are no more lines
while (line != null) {
//replace any spaces with empty string
//first argument is regex matching any empty spaces, second is replacement
line = line.replaceAll("\\s+", "");
//append the current line
stringBuilder.append(line);
//read the next line, will be null when there are no more
line = reader.readLine();
}
System.out.println(stringBuilder);
} catch (IOException exc) {
exc.printStackTrace();
}
}
First of all read on try with resources, when you are using it you don't need to close manually resources(files, streams, etc.), it will do it for you. This for example.
You don't need to wrap read lines in StringBuffer, you don't get anything out of it in this case.
Also read about the methods provided by String class starting with the java doc - documentation.
I have a code which replace some characters (space, tabulator) of string introduced by the user, and then shows the text:
System.out.println("Text:");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
try {
String text = bufferedReader.readLine();
text = text.replaceAll("\n", "");
text = text.replaceAll(" ", "");
text = text.replaceAll("\t", "");
System.out.println(text);
} catch (IOException e) {
}
But when I paste a text of varios lines:
First Substring Introduced
Second Substring Introduced
Third Substring Introduced
it shows just the substring before the first newline like:
firstSubtringIntroduced
I want to obtain the next result of whole pasted text:
FirstSubstringIntroducedSecondSubstringIntroducedThirdSubstringIntroduced
You are reading just one line, the first one:
String text = bufferedReader.readLine(); //just one line
That's why you got that output that only shows the first line processed. You should make a loop in order to read all of the lines you are entering:
while((text=bufferedReader.readLine())!=null)
{
text = text.replaceAll("\n", "");
text = text.replaceAll(" ", "");
text = text.replaceAll("\t", "");
System.out.print(text);
}
The first loop will print FirstSubtringIntroduced, the second SecondSubstringIntroduced, and so on, until all the lines are processed.
Try aggregating all lines together, after removing tab and space from each line:
StringBuilder sb = new StringBuilder();
String text = "";
try {
while ((text = br.readLine()) != null) {
text = text.replaceAll("[\t ]", "");
sb.append(text);
}
}
catch (IOException e) {
}
System.out.println(sb);
The issue here is that your BufferedReader is reading one line at a time.
As an alternative, and closer to your current solution, you could just using System.out.print, which does not automatically print a newline, instead of System.out.println:
try {
while ((text = br.readLine()) != null) {
text = text.replaceAll("[\t ]", "");
System.out.print(text);
}
}
catch (IOException e) {
}
Note that String#replaceAll expects a regular expression. String#replace replaces all occurrences of the first argument with the second argument (which is what you want).
System.out.println(text.replace("\n", "").replace("\r", ""));
The method names are a little bit confusing.
public static void main(String args[]) {
System.out.println("Text:");
StringBuilder stringBuilder = new StringBuilder();
try (InputStreamReader inputStreamReader = new InputStreamReader(System.in);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
Scanner scanner = new Scanner(bufferedReader);
) {
while (scanner.hasNext()) {
stringBuilder.append(scanner.next());
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(stringBuilder.toString());
}
I do think this is what you need.
I have a java program that can read multiple files and replace values accordingly. However, I am struggling to apply a condition to it and apply the changes only when a certain condition is met. For example, if the file contains this specific character ':20:' then apply the changes otherwise leave the text file as it is.
The problem here is, since I don't have fields to look for to apply the condition accordingly I don't know how these can be applied to such a text file which contains just data like : (12345555555) 233344 100 :20:aaa.
I also looked at using the contains() method to look into the file to find the value I want then apply the changes but couldn't make it work.
public class TextFm
{
public static void main(String[] args)
{
File folder = new File("C:\\tmp");
File[] listOfFiles = folder.listFiles();
for(File file : listOfFiles)
{
replaceText(file);
}
}
public static void replaceText(File file)
{
try
{
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while ((line = reader.readLine()) != null)
{
oldtext = oldtext + line + System.lineSeparator();
}
reader.close();
String replacedtext = oldtext.replaceAll("100", "200");
FileWriter writer = new FileWriter(file);
writer.write(replacedtext);
writer.close();
System.out.println("Done");
} catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
Using contains() method will work fine in this case. You can do that like this:
String line = "", oldtext = "";
while ((line = reader.readLine()) != null)
{
oldtext = oldtext + line + System.lineSeparator();
}
reader.close();
if(oldtext.contains(":20:")) {
String replacedtext = oldtext.replaceAll("100", "200");
FileWriter writer = new FileWriter(file);
writer.write(replacedtext);
writer.close();
System.out.println("Done");
}
public static void replaceText(File file)
{
try
{
Charset charset = Charsets.defaulCharset();
String oldText = new String(Files.readAllBytes(file.toPath()),
charset);
if (!oldText.contains(":20")) {
return;
}
if (!oldText.matches("(?s).*you (idiot|unspeakable).*")) {
return;
}
String replacedtext = oldtext.replace("100", "200");
replacedtext = replacedtext .replaceAll("\\d", "X"); // Digit X-ed out
if (!replacedText.equals(oldText)) {
Files.write(file.toPath(), replacedText.getBytes(charset));
}
System.out.println("Done");
} catch (IOException ioe)
{
ioe.printStackTrace();
}
}
For speed one should not collect the file contents with a String and +. Better use a StringBuilder, or the very nice Files class.
Finding text goes either by contains or by a regular expression match.
Replacement can be done by either too.
The replace, replaceFirst and replaceAll methods return the original string when nothing could be replaced.
Regex (?s) lets . (=any char) also match line breaks.
I have a file with text in this format:
text:text2:text3
text4:text5:text6
text7:text8:text9
Now what I want to do, is to read the first line, separate the words at the ":", and save the 3 strings into different variables. those variables are then used as parameter for a method, before having the program read the next line and doing the same thing over and over again.. So far I've got this:
public static void main(String[] args) {
BufferedReader reader = null;
try {
File file = new File("C://Users//Patrick//Desktop//textfile.txt");
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Also, I've tried this for separation (although not sure Array is the best option:
String[] strArr = sCurrentLine.split("\\:");
Use String[] parts = line.split(":"); to get an array with text, text2 etc. You can then loop through parts and call the method you want with each item in the list.
Your original split does not work, because : is not a special character in Regex. You only have to use an escape character when the split you are trying to achieve uses a special character.
More information here.
try {
BufferedReader br = new BufferedReader(new FileReader("Help.txt"));
String helptext = br.readLine();
helpText.setText(helptext);
} catch (IOException e) {
System.out.println ("Error: " + e);
}
It only returns the first line of the text file and the text file is about 4 pages long.
"helptext" being a text area.I want the whole file with its spaces I made in the text area.
This will give only 1 line where in your file the first line whatever contain to get all the line you need get into the loop
StringBuffer sb = new StringBuffer();
String line = null;
while((line=br.readLine()) !=null){
sb.append(line);
}
helpText.setText(sb.toString());
You need to loop through the text file. You are only telling it to readline() one time.
EDIT: Fixed code to be exactly what user needed
EDIT 2: Added code to keep cursor at top
String line;
try {
BufferedReader br = new BufferedReader(new FileReader("<Location of text file>"));
while((line=br.readLine()) != null){
helpText.append(line);
//Add a new line for the next entry (If you would like)
helpText.append("\n");
}
//Set Cursor back to start
helpText.setCaretPosition(WIDTH);
}
catch (IOException e) {
System.out.println (e);
}
you have to read every line in a loop.
String line = br.readLine();
String helptext = "";
while(line != null) {
helptext = helptext + line;
line = br.readLine();
}
helpText.setText(helptext);