I want to extract the first String in a file using the delimiter ",".
Why does this code generate a number of lines greater than one?
public static void main(String[] args) {
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("irisAfter.txt"));
String read = null;
while ((read = in.readLine()) != null) {
read = in.readLine();
String[] splited = read.split(",");
for (int i =0; i<splited.length;i++) {
System.out.println(splited[0]);
}
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception e) { e.printStackTrace(); }
}
}
You are printing inside a loop. That's why it is printing multiple times (if that's what you're asking).
String[] splited = read.split(",");
System.out.println(splited[0]);
will just do
EDIT: As Abishek also mentioned, don't read = in.readLine(); again inside your while loop since by doing so you are skipping a line.
while ((read = in.readLine()) != null) {
String[] splited = read.split(",");
System.out.println(splited[0]);
}
What do you mean by number of lines superior to the original ones
If you are using splited[0], why are you keeping inside a loop. It will always get you same string
Not sure why your code works that way but you might try Scanner with a delimeter. Try:
Scanner sc = new Scanner( new File("myNumbers")).useDelimiter(",");
String firstString = sc.next();
/// check for null..
You read in every line from "irisAfter.txt", then split each line on "," into multiple elements, then print out the first element of that line on its own line as many times as there are elements in the line. Multiple lines*multiple elements per line = more lines in output than in input.
Change
for (int i =0; i<splited.length;i++) {
System.out.println(splited[0]);
}
to
if (splited.length > 0)
{
System.out.println(splited[0]);
}
That way you print out the first element of every line on its own line only one time and only if there actually is a first element.
You are also skipping every other line. If you don't want to do that, remove the line
read = in.readLine();
just below
while ((read = in.readLine()) != null) {.
(You are now reading in a line and then reading in the next line, discarding the first read in line. Then you process that second line, after which the loop starts again, you read in the third line, then read in the fourth line, discarding the third, etc. etc.)
if you modify your code like this, you should get the result you expect.
public static void main(String[] args) {
BufferedReader in = null;
try {
String[] splited;
in = new BufferedReader(new FileReader("irisAfter.txt"));
String read = null;
while ((read = in.readLine()) != null) {
read = in.readLine();
splited = read.split(",");
}
System.out.println(splited[0]);
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception e) {
}
}
}
Related
I am trying to write a program that will read line n of a provided text file, using a BufferedReader, and convert this line's contents into an int. This is the code I am currently using, but it fails to output an int:
BufferedReader reader = null;
int LineContent;
try {
File file = new File("C:\\Users\\Admin\\Desktop\\SAVEdata\\Save.txt");
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
LineContent = Integer.parseInt(line);
if (LineContent == 0) {
CHRSelectWorld w = new CHRSelectWorld();
Greenfoot.setWorld(w);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
You are trying to read and parse every line in your file. If you want nth line, you can use Files class
String line = Files.readAllLines(Paths.get("file.txt")).get(n);
It will work well for files of small-medium size.
long n = 42L;
Path path = Paths.get(
"C:\\Users\\Admin\\Desktop\\SAVEdata\\Save.txt");
Optional<String> line =
Files.lines(path, Charset.defaultCharset())
.skip(n - 1)
.findFirst();
if (line.isEmpty()) {
System.out.println("Insufficient lines, less than " + n);
}
System.out.println(line.orElse("(No line found)");
The class Files has many goodies, and with streams it is almost a one-liner.
Hi I using following code
public class Readfiles {
FileInputStream fr;
public void readAll(){
try {
fr = new FileInputStream(new File("books/Artificial intelligence.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("File Not Found");
e.printStackTrace();
}
CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
decoder.onMalformedInput(CodingErrorAction.IGNORE);
InputStreamReader reader = new InputStreamReader(fr, decoder);
BufferedReader br = new BufferedReader(reader);
try {
int i = 0;
for(String newLine; (newLine = br.readLine()) != null; )
{
newLine = br.readLine();
i++;
System.out.println(newLine);
}
br.close();
System.out.println(i);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
To read this txt file it is about 420.000 lines long:
Artificial intelligence.txt
But my code above dont read it correctly it is missing about half of the lines in the middle, and seems to start anywhere (each start randomly) the following is one of the possible result of the SYSOut :
Only first lines:
##Margaret H. Szymanski,Paul M. Aoki,Rebecca E. Grinter,Amy Hurst,James D. Thornton,Allison Woodruff
#cComputer Supported Cooperative Work
#%5488
#%87739
#%257074
#%818174
#!
#*Unpacking Tasks: The Fusion of New Technology with Instructional Work.
#t2008
#index831790
#%174882
#!
So the question is Why?
Printout of i is always 209647.
Well you are reading the line twice
once in
for(String newLine; (newLine = br.readLine()) != null; )
{
and then again in
newLine = br.readLine();
nicer would be
while ((newLine = br.readLine()) != null) {....}
You're calling br.readLine() twice in your loop, but only using the result of one of those two calls in your System.out.println call. So you're only printing out every second line.
You're calling br.readLine() twice
for(String newLine; (newLine = br.readLine()) != null; )
{
newLine = br.readLine();
i++;
System.out.println(newLine);
}
You can get rid of the one inside the loop
for(String newLine; (newLine = br.readLine()) != null; )
{
i++;
System.out.println(newLine);
}
for(String newLine; (newLine = br.readLine()) != null; )
{
i++;
System.out.println(newLine);
}
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
the following code will only read the first line of a text file and it will stop there. I've been experimenting with loops but i cannot get it to successfully update the line until there are no more lines in the file. can anyone help? thanks
public void readFile(){
try {
BufferedReader in = new BufferedReader(new FileReader("test1.txt"));
words = new ArrayList<Word>();
int lineNum = 1; // we read first line in start
// delimeters of line in this example only "space"
char [] parse = {' '};
String delims = new String(parse);
String line = in.readLine();
String [] lineWords = line.split(delims);
// split the words and create word object
for (int i = 0; i < lineWords.length; i++) {
Word w = new Word(lineWords[i]);
words.add(w);
}
lineNum++; // pass the next line
line = in.readLine();
in.close();
} catch (IOException e) {
}
}
Basically, you want to keep reading until you run out of lines, at which time BufferedReader will return null
char[] parse = {' '};
String delims = new String(parse);
String line = null;
while ((line = in.readLine()) != null) {
String[] lineWords = line.split(delims);
// split the words and create word object
for (int i = 0; i < lineWords.length; i++) {
Word w = new Word(lineWords[i]);
words.add(w);
}
lineNum++; // pass the next line
}
You should be managing your resources better, if you open it, you should make all reasonable attempts to close. Currently, if your code fails for some reason, the in.close line will never be called. Also, you shouldn't ignore exceptions
Luckily, in Java 8, this is easy to manage...
try (BufferedReader in = new BufferedReader(new FileReader("test1.txt"))) {
//...
} catch (IOException e) {
e.printStackTrace();
}
Take a closer look at Basic I/O, The try-with-resources Statement and BufferedReader JavaDocs, especially BufferedReader#readLine
You may also want to take a look at LineNumberReader ;)
while((line = in.readLine()) != null){
//process line
}
This nested statement reads a line from the BufferedReader and stores it in line. At the end of the file, readLine() will return null and stop the loop.
So I am trying to extract a piece of code from a txtfile ,the start of the piece being indicated by "# EMPIRES" and the end being indicated by another string starting with a '#'. My program however never finds the start of the piece and keeps on going until it reaches the end of the file.
To try and find out what the problem was I tried first to print every line that it finds.
And here I encountered another problem. My code already stops finding new lines,long before
"# EMPIRES" is even reached.
public String getEmpirestxt(String fileName) {
Scanner sc;
try {
sc = new Scanner(new File(fileName));
String currentLine = sc.nextLine();
StringBuilder empiresText = new StringBuilder(currentLine);
while (!currentLine.startsWith("# EMPIRES")) {
currentLine = sc.nextLine();
System.out.println(currentLine);
}
currentLine = sc.nextLine();
while (sc.hasNextLine() && currentLine.charAt(0)!='#') {
empiresText.append("\n").append(sc.nextLine());
}
return empiresText.toString();
} catch (FileNotFoundException ex) {
System.out.println("Landed_Titles.txt not found.");
}
return null;
}
The textfile itself :
https://www.wetransfer.com/downloads/a1093792d5ac54b6ccce04afecb9357f20140402095042/505fca
Here is my solution to your problem. I used newBufferedReader instead of the Scanner to read the file. This example works with Java 7.
public String getEmpirestxt2(String fileName) {
Charset charset = Charset.forName("ISO-8859-1");
Path filePath = Paths.get(fileName);
try (BufferedReader reader = Files.newBufferedReader(filePath, charset)) {
String line = null;
// find the start of the piece
while ((line = reader.readLine()) != null && !line.equals(START)) {
}
System.out.println("START: " + line);
// getting the piece
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null && !line.startsWith(END)) {
sb.append(line);
}
System.out.println("END: " + line);
return sb.toString();
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
}
return null;
}
The constants in the method are:
private static final String START = "# EMPIRES";
private static final String END = "#";
I tested it with your file and it works fine. It also prints the starting and end points of the required piece:
START: # EMPIRES
END: # color={ 144 80 60 }
String currentLine = sc.nextLine();
you are starting reading from the next Line.
The condition:
while (sc.hasNextLine() && currentLine.charAt(0)!='#')
may terminate even if the file has more lines to read, because of the second predicate. If currentLine.charAt(0)!='#' is fales, the while loop ends. This does not mean there are no more lines to read.
In your second while loop you never set currentLine
This part:
currentLine = sc.nextLine();
while (sc.hasNextLine() && currentLine.charAt(0)!='#') {
empiresText.append("\n").append(sc.nextLine());
}
should be:
do{
currentLine=sc.nextLine();
empiresText.append("\n").append(sc.nextLine());
}while(sc.hasNextLine() && currentLine.charAt(0)!='#');
Otherwise the line right after # EMPIRES won't be read and the code while loop will never stop because the currentLine is not getting updated.
Append currentLine instead of sc.nextLine() in the second while loop :
while (sc.hasNextLine() && currentLine.charAt(0) != '#') {
empiresText.append("\n").append(currentLine);
currentLine = sc.nextLine();
}
Otherwise you can use a single loop like below :
while (sc.hasNextLine()){
if(sc.nextLine().startsWith("# EMPIRES")){
currentLine = sc.nextLine();
while (sc.hasNextLine() && currentLine.charAt(0) != '#') {
empiresText.append("\n").append(currentLine);
currentLine = sc.nextLine();
}
}
}