public static void main(String[] args) throws MalformedURLException, IOException
{
// TODO code application logic here
URL link1 = new URL("xmlFileHere");
InputStream xml = link1.openStream();
InputStreamReader reader = new InputStreamReader(xml);
BufferedReader reader1 = new BufferedReader(reader);
while(reader1.readLine()!= null)
{
System.out.println(reader1.readLine());
}
}
Hello. As you can see my BufferedReader is not reading the whole online XML file, I don't know why. Any idea why this happens?
Thank you.
while(reader1.readLine()!= null) // reading here
{
System.out.println(reader1.readLine()); // and here
}
You are skipping a line each time you loop...
Do,
String line=null;
while((line=reader1.readLine())!= null) // reading here
{
System.out.println(line); // and displaying here
}
Consider using Scanner which thanks to hasNextLine() method makes iterating more intuitive.
Scanner scanner = new Scanner(reader1);
while (scanner.hasNextLine() ) {//check if next line exists
System.out.println(scanner.nextLine());//use this next line
}
scanner.close();
I prefer this idiom
for (String curLine; (curLine=reader1.readLine()) != null;) {
System.out.println(curLine);
}
it's good because curLine var is needed only inside loop
Change this in your code.
String curLine = "";
while((curLine=reader1.readLine())!= null)
{
System.out.println(curLine);
}
reader1.readLine() will read your line in while loop and again inside while loop which create problem in not displaying whole XML file.
Change the while loop.
String line;
while( (line=reader1.readLine() ) != null)
{
System.out.println(line);
}
Related
I have some very simple code to ready content of txt file, line by line and put it into String[], however buffered reader return all lines as "null" - any idea on what might be the reason? *I want to use buffered reader and not other options as this is just part of java training excersise and mostly I want to understand where is the mistake i made. thanks!
public static void readFile (String path){
File file = new File(path);
try {
BufferedReader br = new BufferedReader(new FileReader(file));
int lineCount = (int) br.lines().count();
String[] passwords = new String[lineCount];
for (int i=0; i<lineCount; i++){
passwords[i] = br.readLine();;
System.out.println(passwords[i]);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
By using the lines() method you basically move the buffered reader position to the end of the file. It's like you already read these lines.
Try using this in order to iterate through all lines:
while ((line = br.readLine()) != null) {
// Use the line variable here
}
Use br.lines() or br.readLine() to consume the input, but not both at the same time. This version does the same using just the stream to String[], and closes the inputs in try with resources block:
public static String[] readFile(Path path) throws IOException {
try (BufferedReader br = Files.newBufferedReader(path);
Stream<String> stream = br.lines()) {
return stream.peek(System.out::println)
.collect(Collectors.toList())
.toArray(String[]::new);
}
}
String[] values = readFile(Path.of("somefile.txt"));
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.
How do you read and display data from .txt files?
BufferedReader in = new BufferedReader(new FileReader("<Filename>"));
Then, you can use in.readLine(); to read a single line at a time. To read until the end, write a while loop as such:
String line;
while((line = in.readLine()) != null)
{
System.out.println(line);
}
in.close();
If your file is strictly text, I prefer to use the java.util.Scanner class.
You can create a Scanner out of a file by:
Scanner fileIn = new Scanner(new File(thePathToYourFile));
Then, you can read text from the file using the methods:
fileIn.nextLine(); // Reads one line from the file
fileIn.next(); // Reads one word from the file
And, you can check if there is any more text left with:
fileIn.hasNext(); // Returns true if there is another word in the file
fileIn.hasNextLine(); // Returns true if there is another line to read from the file
Once you have read the text, and saved it into a String, you can print the string to the command line with:
System.out.print(aString);
System.out.println(aString);
The posted link contains the full specification for the Scanner class. It will be helpful to assist you with what ever else you may want to do.
In general:
Create a FileInputStream for the file.
Create an InputStreamReader wrapping the input stream, specifying the correct encoding
Optionally create a BufferedReader around the InputStreamReader, which makes it simpler to read a line at a time.
Read until there's no more data (e.g. readLine returns null)
Display data as you go or buffer it up for later.
If you need more help than that, please be more specific in your question.
I love this piece of code, use it to load a file into one String:
File file = new File("/my/location");
String contents = new Scanner(file).useDelimiter("\\Z").next();
Below is the code that you may try to read a file and display in java using scanner class. Code will read the file name from user and print the data(Notepad VIM files).
import java.io.*;
import java.util.Scanner;
import java.io.*;
public class TestRead
{
public static void main(String[] input)
{
String fname;
Scanner scan = new Scanner(System.in);
/* enter filename with extension to open and read its content */
System.out.print("Enter File Name to Open (with extension like file.txt) : ");
fname = scan.nextLine();
/* this will reference only one line at a time */
String line = null;
try
{
/* FileReader reads text files in the default encoding */
FileReader fileReader = new FileReader(fname);
/* always wrap the FileReader in BufferedReader */
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
System.out.println(line);
}
/* always close the file after use */
bufferedReader.close();
}
catch(IOException ex)
{
System.out.println("Error reading file named '" + fname + "'");
}
}
}
If you want to take some shortcuts you can use Apache Commons IO:
import org.apache.commons.io.FileUtils;
String data = FileUtils.readFileToString(new File("..."), "UTF-8");
System.out.println(data);
:-)
public class PassdataintoFile {
public static void main(String[] args) throws IOException {
try {
PrintWriter pw = new PrintWriter("C:/new/hello.txt", "UTF-8");
PrintWriter pw1 = new PrintWriter("C:/new/hello.txt");
pw1.println("Hi chinni");
pw1.print("your succesfully entered text into file");
pw1.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new FileReader("C:/new/hello.txt"));
String line;
while((line = br.readLine())!= null)
{
System.out.println(line);
}
br.close();
}
}
In Java 8, you can read a whole file, simply with:
public String read(String file) throws IOException {
return new String(Files.readAllBytes(Paths.get(file)));
}
or if its a Resource:
public String read(String file) throws IOException {
URL url = Resources.getResource(file);
return Resources.toString(url, Charsets.UTF_8);
}
You most likely will want to use the FileInputStream class:
int character;
StringBuffer buffer = new StringBuffer("");
FileInputStream inputStream = new FileInputStream(new File("/home/jessy/file.txt"));
while( (character = inputStream.read()) != -1)
buffer.append((char) character);
inputStream.close();
System.out.println(buffer);
You will also want to catch some of the exceptions thrown by the read() method and FileInputStream constructor, but those are implementation details specific to your project.
I am not being able to print all the output in file.BufferedWriter is not working well.What is my mistake to save the output of the program in file.
public class delete {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
int alphabet=0;
char ch;
int n=0;
String line;
BufferedReader br = new BufferedReader(new FileReader("InputFileLocation"));
line= br.readLine();
while ((line = br.readLine()) != null) {
for(int i=0;i<line.length();i++){
ch=line.charAt(i);
if(ch=='a')
alphabet ++;
}
BufferedWriter bw = new BufferedWriter(new FileWriter("OutputFileLocation"));
n++;
System.out.println("case#"+n+":"+alphabet);
bw.write(String.valueOf(alphabet));
bw.close();
alphabet=0;
}
br.close();
}
}
Without running this I notice that you discard the first line by retrieving it, then retrieving another line in the first run of your condition.
Also, if you are writing every line to the output file then you probably want to move your initialization of bw outside your while loop. At the very least you want to use the FileWriter(String, boolean) constructor instead of creating a new file.
Dont create new BufferedWriter in the loop, thats a bad design.
you could try putting bw.flush() before closing it.
bw.close() implicitly call flush, but I had similar problem with this, I had to call flush explicitly to work.
Im trying to read a simple text file with contents
input.txt
Line 1
Line 2
Line 3
But it always goes to the exception and prints Error.
import java.io.*;
import java.util.*;
public class Main {
public static void main(String args[]){
List<String> text = new ArrayList<String>();
try{
BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
for (String line; (line = reader.readLine()) != null; ) {
text.add(line);
}
System.out.println(text.size()); //print how many lines read in
reader.close();
}catch(IOException e){
System.out.println("ERROR");
}
}
}
Im using Eclipse as my IDE if that makes a difference. I've tried this code on http://www.compileonline.com/compile_java_online.php
and it runs fine, why wont it run in Eclipse?
give complete file path like "C:\\folder_name\\input.txt" or place input.txt inside src directory of eclipse project.
public class Main {
public static void main(String args[]){
List<String> text = new ArrayList<String>();
try{
BufferedReader reader = new BufferedReader(
new FileReader("input.txt")); //<< your problem is probably here,
//More than likely you have to supply a path the input file.
//Something like "C:\\mydir\\input.txt"
for (String line; (line = reader.readLine()) != null; ) {
text.add(line);
}
System.out.println(text.size()); //print how many lines read in
reader.close();
}catch(IOException e){
System.out.println("ERROR"); //This tells you nothing.
System.out.println(e.getMessage()); //Do this
//or
e.printStackTrace(); //this or both
}
}
}
You most likely have a bad path. Consider this main instead:
public class Main {
public static void main(String args[]) throws Exception {
List<String> text = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
for (String line; (line = reader.readLine()) != null; ) {
text.add(line);
}
System.out.println(text.size()); //print how many lines read in
reader.close();
}
}
The "throws Exception" addition allows you to focus on the code, and consider better error handling later. Also consider using File f = new File("input.txt") and use that, because it allows you to print out f.getAbsolutePath() which tells you the filename it was actually looking for.
Changing input.txt to src\\input.txt solved the problem!
I guess it was because the current directory isnt actually the src folder its the parent,
Thanks for the help!