Java read certain line from txt file - java

I want to read the 2nd line of text from a file and have that put into an array. I already have it working on the first line.
[ Code removed as requested ]
The while loop above shows how I read and save the 1st line of the text file into an array. I wish to repeat this process from the 2nd line only into a different array.
File Content:
Sofa,Armchair,Computer Desk,Coffee Table,TV Stand,Cushion,Bed,Mattress,Duvet,Pillow
599.99,229.99,129.99,40.00,37.00,08.00,145.00,299.99,24.99,09.99

Just get rid of the first readLine() call, and move the String.split() call into the loop.

Simply use the BufferedReader class to read the entire file and then manipulate the String output.
Something along these lines
public static String readFile(String fileName) throws IOException {
String toReturn = "";
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("test.txt"));
while ((sCurrentLine = br.readLine()) != null) {
toReturn = toReturn+"\n"+sCurrentLine;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return toReturn;
}
would yield a String which can then be easily used.

public static void main(String[] args)
{
String filePath = args[0];
String[] lineElements = getLine(filePath,2).split(",");
}
public static String getLine(String path,int line)
{
List<String> cases = new ArrayList<String>();
try{
BufferedReader br = new BufferedReader(new FileReader(path));
String currLine = "";
while((currLine = br.readLine()) != null){
cases.add(currLine);
}
}catch(IOException ex){
ex.printStackTrace();
}
return cases.get(line - 1);//2nd line
}

Related

bufferedReader - reading out lines in sections from a text file

I have a text file which has a format similar to this:
===Header1====
LINE1
LINE2
LINE3
===Header2====
LINE1
LINE2
LINE3
What I'm trying to do is parse these out individually to a String variable, so when the reader detects "====Header1====", it will also read all lines underneath til it detects "===Header2===", which will be variable Header1 and so on
Im having issues at the moment with reading out the lines till it detects the next header. I was wondering could anyone shed some light on this? Here is what i have so far
try (BufferedReader br = new BufferedReader(new FileReader(FILE))) {
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
if (sCurrentLine.startsWith("============= Header 1 ===================")) {
System.out.println(sCurrentLine);
}
if (sCurrentLine.startsWith("============= Header 2 ===================")) {
System.out.println(sCurrentLine);
}
if (sCurrentLine.startsWith("============= Header 3 ===================")) {
System.out.println(sCurrentLine);
}
}
} catch (IOException e) {
e.printStackTrace();
}
You can create a readLines() method which will read the lines till the next header and loads the lines to an arraylist, call readLines() from main() as shown in the below code with inline comments:
public static void main(String[] args) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(new File(FILE)));
//read the 2rd part of the file till Header2 line
List<String> lines1 = readLines(br,
"============= Header 2 ===================");
//read the 2rd part of the file till Header3 line
List<String> lines2 = readLines(br,
"============= Header 3 ===================");
//read the 3rd part of the file till end
List<String> lines3 = readLines(br, "");
} catch (IOException e) {
e.printStackTrace();
} finally {
//close BufferedReader
}
}
private static List<String> readLines(BufferedReader br, String nextHeader)
throws IOException {
String sCurrentLine;
List<String> lines = new ArrayList<>();
while ((sCurrentLine = br.readLine()) != null) {
if("".equals(nextHeader) ||
(nextHeader != null &&
nextHeader.equals(sCurrentLine))) {
lines.add(sCurrentLine);
}
}
return lines;
}

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

How to read in information from a file, and store it as a string. Java

ive gotten this far, but this doesnt work to read in the file, thats the part im stuck on. i know that you need to use the scanner, but im not sure what im missing here. i think it needs a path to the file also, but i dont know where to put that in
public class string
{
public static String getInput(Scanner in) throws IOException
{
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter file");
String filename =keyboard.next();
File inputFile = new File(filename);
Scanner input = new Scanner(inputFile);
String line;
while (input.hasNext())
{
line= input.nextLine();
System.out.println(line);
}
input.close();
}
if(filename.isEmpty())
{
System.out.println("Sorry, there has been an error. You must enter a string! (A string is some characters put together.) Try Again Below.");
return getInput(in);
}
else
{
return filename;
}
}
public static int getWordCount(String input)
{
String[] result = input.split(" ");
return result.length;
}
public static void main(String[] args)
{
DecimalFormat formatter = new DecimalFormat("0.##");
String input = getInput(new Scanner(System.in));
float counter = getWordCount(input);
System.out.println("The number of words in this string ("+input+") are: " + counter);
Scanner keyboard= new Scanner(System.in);
}
}
//end of code
First of all, when doing file I/O in Java, you should properly handle all exceptions and errors that can occur.
In general, you need to open streams and resources in a try block, catch all exceptions that happen in a catch block and then close all resources in a finally block. You should read up more on these here as well.
For using a Scanner object, this would look something like:
String token = null;
File file = null;
Scanner in = null;
try {
file = new File("/path/to/file.txt");
in = new Scanner(file);
while(in.hasNext()) {
token = in.next();
// ...
}
} catch (FileNotFoundException e) {
// if File with that pathname doesn't exist
e.printStackTrace();
} finally {
if(in != null) { // pay attention to NullPointerException possibility here
in.close();
}
}
You can also use a BufferedReader to read a file line by line.
BufferedReader reader = new BufferedReader(new FileReader("/path/to/file.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
// ...
}
With added exception handling:
String line = null;
FileReader fReader = null;
BufferedReader bReader = null;
try {
fReader = new FileReader("/path/to/file.txt");
bReader = new BufferedReader(fReader);
while ((line = bReader.readLine()) != null) {
// ...
}
} catch (FileNotFoundException e) {
// Missing file for the FileReader
e.printStackTrace();
} catch (IOException e) {
// I/O Exception for the BufferedReader
e.printStackTrace();
} finally {
if(fReader != null) { // pay attention to NullPointerException possibility here
try {
fReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bReader != null) { // pay attention to NullPointerException possibility here
try {
bReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In general, use the Scanner for parsing a file, and use the BufferedReader for reading the file line by line.
There are other more advanced ways to perform reading/writing operations in Java. Check out some of them here

How to extract starting of a String in Java

I have a text file with more than 20,000 lines and i need to extract specific line from it. The output of this program is completely blank file.
There are 20,000 lines in the txt file and this ISDN line keeps on repeating lots of time each with different value. My text file contains following data.
RecordType=0(MOC)
sequenceNumber=456456456
callingIMSI=73454353911
callingIMEI=85346344
callingNumber
AddInd=H45345'1
NumPlan=H34634'2
ISDN=94634564366 // Need to extract this "ISDN" line only
public String readTextFile(String fileName) {
String returnValue = "";
FileReader file = null;
String line = "";
String line2 = "";
try {
file = new FileReader(fileName);
BufferedReader reader = new BufferedReader(file);
while ((line = reader.readLine()) != null) {
// extract logic starts here
if (line.startsWith("ISDN") == true) {
System.out.println("hello");
returnValue += line + "\n";
}
}
} catch (FileNotFoundException e) {
throw new RuntimeException("File not found");
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return returnValue;
}
We will assume that you use Java 7, since this is 2014.
Here is a method which will return a List<String> where each element is an ISDN:
private static final Pattern ISDN = Pattern.compile("ISDN=(.*)");
// ...
public List<String> getISDNsFromFile(final String fileName)
throws IOException
{
final Path path = Paths.get(fileName);
final List<String> ret = new ArrayList<>();
Matcher m;
String line;
try (
final BufferedReader reader
= Files.newBufferedReader(path, StandardCharsets.UTF_8);
) {
while ((line = reader.readLine()) != null) {
m = ISDN.matcher(line);
if (m.matches())
ret.add(m.group(1));
}
}
return ret;
}

How to print lines from a file that contain a specific word using java?

How to print lines from a file that contain a specific word using java ?
Want to create a simple utility that allows to find a word in a file and prints the complete line in which given word is present.
I have done this much to count the occurence but don't knoe hoe to print the line containing it...
import java.io.*;
public class SearchThe {
public static void main(String args[])
{
try
{
String stringSearch = "System";
BufferedReader bf = new BufferedReader(new FileReader("d:/sh/test.txt"));
int linecount = 0;
String line;
System.out.println("Searching for " + stringSearch + " in file...");
while (( line = bf.readLine()) != null)
{
linecount++;
int indexfound = line.indexOf(stringSearch);
if (indexfound > -1)
{
System.out.println("Word is at position " + indexfound + " on line " + linecount);
}
}
bf.close();
}
catch (IOException e)
{
System.out.println("IO Error Occurred: " + e.toString());
}
}
}
Suppose you are reading from a file named file1.txt Then you can use the following code to print all the lines which contains a specific word. And lets say you are searching for the word "foo".
import java.util.*;
import java.io.*;
public class Classname
{
public static void main(String args[])
{
File file =new File("file1.txt");
Scanner in = null;
try {
in = new Scanner(file);
while(in.hasNext())
{
String line=in.nextLine();
if(line.contains("foo"))
System.out.println(line);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
Hope this code helps.
public static void grep(Reader inReader, String searchFor) throws IOException {
BufferedReader reader = null;
try {
reader = new BufferedReader(inReader);
String line;
while ((line = reader.readLine()) != null) {
if (line.contains(searchFor)) {
System.out.println(line);
}
}
} finally {
if (reader != null) {
reader.close();
}
}
}
Usage:
grep(new FileReader("file.txt"), "GrepMe");
Have a look at BufferedReader or Scanner for reading the file.
To check if a String contains a word use contains from the String-class.
If you show some effort I'm willing to help you out more.
you'll need to do something like this
public void readfile(){
try {
BufferedReader br;
String line;
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream("file path"), "UTF-8");
br = new BufferedReader(inputStreamReader);
while ((line = br.readLine()) != null) {
if (line.contains("the thing I'm looking for")) {
//do something
}
//or do this
if(line.matches("some regular expression")){
//do something
}
}
// Done with the file
br.close();
br = null;
}
catch (Exception ex) {
ex.printStackTrace();
}
}

Categories

Resources