How would I print out the first word of each line? - java

I have a text file that reads like this:
1. Bananas that are not green
2. Pudding that is not vanilla
3. Soda that is not Pepsi
4. Bread that is not stale
I just want it to print out the first word of each line
NOT INCLUDING NUMBERS!
It should print out as:
Bananas
Pudding
Soda
Bread
Here is my code:
public static void main(String[] args) {
BufferedReader reader = null;
ArrayList <String> myFileLines = new ArrayList <String>();
try {
String sCurrentLine;
reader = new BufferedReader(new
FileReader("/Users/FakeUsername/Desktop/GroceryList.txt"));
while ((sCurrentLine = reader.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
System.out.print(e.getMessage());
} finally {
try {
if (reader != null)reader.close();
} catch (IOException ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
}

Use the split function of String. It returns the array of the String as per the character which we want to split with the string. In your case, it is like as follow.
String sCurrentLine = new String();
reader = new BufferedReader(new
FileReader("/Users/FakeUsername/Desktop/GroceryList.txt"));
while ((sCurrentLine = reader.readLine() != null) {
String words[] = sCurrentLine.split(" ");
System.out.println(words[0]+" "+words[1]);
}

Java 8+ you can use the BufferedReader's lines() method to do this very easily:
String filename = "Your filename";
reader = new BufferedReader(new FileReader(fileName));
reader.lines()
.map(line -> line.split("\\s+")[1])
.forEach(System.out::println);
Output:
Bananas
Pudding
Soda
Bread
This will create a Stream of all the lines in the BufferedReader, split each line on whitespace, and then take the second token and print it

Please try the code below -:
outerWhileLoop:
while ((sCurrentLine = reader.readLine()) != null) {
//System.out.println(sCurrentLine);
StringTokenizer st = new StringTokenizer(sCurrentLine," .");
int cnt = 0;
while (st.hasMoreTokens()){
String temp = st.nextToken();
cnt++;
if (cnt == 2){
System.out.println(temp);
continue outerWhileLoop;
}
}
}

Related

Empty line in arraylist Java

protected synchronized static void getRandomProxy(String srcFile) throws FileNotFoundException {
List<String> words = new ArrayList<>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(srcFile));
String line;
while ((line = reader.readLine()) != null) {
words.add(line);
System.out.println(line);
}
int k = 0;
for (int i = 0; i < words.size(); i++) {
k++;
String[] splitted = words.get(i).split(":");
String ip = splitted[0];
String port = splitted[splitted.length - 1];
// System.out.println(k + " " + ip + " * " + port);
}
} catch (IOException iOException) {
} finally {
try {
reader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
I want to get output printed without empty lines .
These are kind of results am getting Like :
result 1.
result 2.
result 3.
i want output like :
result 1.
result 2.
result 3.
without blank lines.
Don't add the String to the list if it's empty :
if(!line.trim().isEmpty()) {
words.add(line);
System.out.println(line);
}
If you still want to add the blank lines to the list but don't display them, just move the condition :
words.add(line);
if(!line.trim().isEmpty())
System.out.println(line);
Doc
Use System.out.print. Note that the file contains a newline char at the end of each line.
If srcFile is created with Notepad, try removing first the carriage return char System.out.print(line.replaceAll("\\r",""))
ArrayList<String> words = new ArrayList<>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(srcFile));
String line;
while ((line = reader.readLine()) != null) {
line = line.trim(); // remove leading and trailing whitespace
if (!line.isEmpty() && !line.equals("")) {
words.add(line);
System.out.println(line);
}
}

When importing a txt file, is there a way to specify how you want it formatted? [duplicate]

How can I open a .txt file and read numbers separated by enters or spaces into an array list?
Read file, parse each line into an integer and store into a list:
List<Integer> list = new ArrayList<Integer>();
File file = new File("file.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
while ((text = reader.readLine()) != null) {
list.add(Integer.parseInt(text));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
}
}
//print out the list
System.out.println(list);
A much shorter alternative is below:
Path filePath = Paths.get("file.txt");
Scanner scanner = new Scanner(filePath);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
} else {
scanner.next();
}
}
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. Although default delimiter is whitespace, it successfully found all integers separated by new line character.
Good news in Java 8 we can do it in one line:
List<Integer> ints = Files.lines(Paths.get(fileName))
.map(Integer::parseInt)
.collect(Collectors.toList());
try{
BufferedReader br = new BufferedReader(new FileReader("textfile.txt"));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}finally{
in.close();
}
This will read line by line,
If your no. are saperated by newline char. then in place of
System.out.println (strLine);
You can have
try{
int i = Integer.parseInt(strLine);
}catch(NumberFormatException npe){
//do something
}
If it is separated by spaces then
try{
String noInStringArr[] = strLine.split(" ");
//then you can parse it to Int as above
}catch(NumberFormatException npe){
//do something
}
File file = new File("file.txt");
Scanner scanner = new Scanner(file);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
}
else {
scanner.next();
}
}
System.out.println(integers);
import java.io.*;
public class DataStreamExample {
public static void main(String args[]){
try{
FileWriter fin=new FileWriter("testout.txt");
BufferedWriter d = new BufferedWriter(fin);
int a[] = new int[3];
a[0]=1;
a[1]=22;
a[2]=3;
String s="";
for(int i=0;i<3;i++)
{
s=Integer.toString(a[i]);
d.write(s);
d.newLine();
}
System.out.println("Success");
d.close();
fin.close();
FileReader in=new FileReader("testout.txt");
BufferedReader br=new BufferedReader(in);
String i="";
int sum=0;
while ((i=br.readLine())!= null)
{
sum += Integer.parseInt(i);
}
System.out.println(sum);
}catch(Exception e){System.out.println(e);}
}
}
OUTPUT::
Success
26
Also, I used array to make it simple.... you can directly take integer input and convert it into string and send it to file.
input-convert-Write-Process... its that simple.

print Float value as it is

I have read a content from a file which is in my local system.It is in float type.So while printing the output I could not get value before the decimal point.What needs to be included so that i will get an exact output.
I want the output like 1.68765 But I am getting .68765
Also i need to append output from another file with this out.
Content of the file will be like this but without double line spaces inbetween.Next to each other but in next next line
1
.
6
8
7
6
5
Here is my code
package testing;
import java.io.*;
class read {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("D:/Movies/test.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
line = br.readLine();
System.out.println(line);
}
} finally {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
As you may see, you're skipping the first line by using the following. You're reading two lines before printing one so the first is skipped.
String line = br.readLine();
while (line != null) {
line = br.readLine();
System.out.println(line);
}
Solution
StringBuilder sb = new StringBuilder();
String line;
while ((line=br.readLine()) != null) {
sb.append(line);
}
float myFloat = Float.valueOf(sb.toString());
Assign the value of the line from the file directly in your loop test. This will save you from headaches and is way more intuitive.
Now since you already have a StringBuilder object, I suggest you append all the lines and then cast its value to a float.
String line = br.readLine(); had read the first line ,use
String line = "";
I suggest using the scanner class to read your input and the nextFloat class to get the next floating point number -
Scanner scanner = new Scanner(new File("D:/Movies/test.txt"));
while(scanner.hasNextFloat()) {
System.out.println(scanner.nextFloat());
}
Basicay you are skipping first line as #yassin-hajaj mentioned, you can solve this in 2 ways:
In JDK8 it would look like this:
Stream<String> lines = Files.lines(Paths.get("D:/Movies/test.txt"));
String valueAsString = lines.collect(Collectors.joining()); // join all characters into a string
Float value = Float.valueOf(valueAsString);// parse it to a float
System.out.printf("%.10f", value); // will print vlaue with 10 digits after comma
Or you can do it by (JDK7+):
StringBuilder sb = new StringBuilder();
try ( BufferedReader br = new BufferedReader(new FileReader("D:/Movies/test.txt"))){ // this will close are streams after exiting this block
String line;
while ((line = br.readLine())!=null) { // read line and assign to line variable
System.out.println(line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("F:/test.txt"));
try {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} finally {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
You can also put the readLine() method within the while condition.
Also, float may not be printed the way you expect, ie, fewer digits will be displayed.
public class Reader {
public static void main(String[] args) throws IOException, NumberFormatException {
BufferedReader br = new BufferedReader(new FileReader("D:/test.txt"));
String line = null;
while ((line = br.readLine()) != null)
System.out.println(Double.parseDouble(line));
br.close();
}
}
Sample output:
1.68765
54.4668489
672.9821368

Removing sentences containing a keyword in java

I am been searching online and on here on how I can remove a line that contains one or two words but I can't find anything on java. This is the code I have right now:
try {
BufferedReader reader = new BufferedReader(new FileReader("Readfile.txt"));
String line = reader.readLine();
while(line !=null)
{
for(int i = 0 ; i<newarray.length;i++){
if(line.contains(newarray[i])){
System.out.println(line);
}
}
line=reader.readLine();
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
It reads sentences from a text file, but before it prints them out, I want to delete some sentences that contains a keyword, e.g. fun.
Something like this:
//BufferedReader stuff etc.
List<String> words = new ArrayList<String>();
words.add("fun");
words.add("something");
String line;
while( (line = br.readLine()) != null)
{
boolean found = false;
for(String word: words)
{
if(line.contains(word))
{
found = true;
break;
}
}
if(found) continue;
System.out.println(line);
}
if(line.contains(newarray[i])){
line = line.replace("fun" ,"");
System.out.println(line);
}
Try this it will delete the word before printing it.

Best way to read data from a file [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Best way to read a text file
In Java I can open a text file like this:
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
My question is, how do you read from the following file? The first line is a number (830) representing number of words, and the following lines contain the words.
830
cooking
English
weather
.
.
I want to read the words into a string array. But how do I read the data first?
You're on the right track; I would treat the first line as a special case by parsing it as an integer (see Integer#parseInt(String)) then reading the words as individual lines:
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
String numLinesStr = reader.readLine();
if (numLinesStr == null) throw new Exception("invalid file format");
List<String> lines = new ArrayList<String>();
int numLines = Integer.parseInt(numLinesStr);
for (int i=0; i<numLines; i++) {
lines.add(reader.readLine());
}
Unless you have some special reason, it's not necessary to keep track of how many lines the file contain. Just use something like this:
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
String line;
while ((line = reader.readLine()) != null) {
// ...
}
If you're working with Java version greater than 1.5, you can also use the Scanner class:
Scanner sc = new Scanner(new File("someTextFile.txt"));
List<String> words = new ArrayList<String>();
int lines = sc.nextInt();
for(int i = 1; i <= lines; i++) {
words.add(sc.nextLine());
}
String[] w = words.toArray(new String[]{});
Try the class java.io.BufferedReader, created on a java.io.FileReader.
This object has the method readLine, which will read the next line from the file:
try
{
java.io.BufferedReader in =
new java.io.BufferedReader(new java.io.FileReader("filename.txt"));
String str;
while((str = in.readLine()) != null)
{
...
}
}
catch(java.io.IOException ex)
{
}
You could use reflection and do this dynamically:
public static void read() {
try {
BufferedReader reader = new BufferedReader(new FileReader(
"filename.txt"));
String line = reader.readLine();
while (line != null) {
if (Integer.class.isAssignableFrom(line.getClass())) {
int number = Integer.parseInt(line);
System.out.println(number);
} else {
String word = line;
System.out.println(word);
}
line = reader.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Categories

Resources