may i know why i am unable to read next line in a .txt file when i upload it.
it happens to all the .txt file that i try to upload and then system.out.println() with.
in my text file it contains : cats,dogs,monkey ( each in one line ) .. but the value out put is:
[Monkey][Monkey, null][Monkey, null, null][Monkey, null, null, null][Monkey, null, null, null, null][Monkey, null, null, null, null, null][Monkey, null, null, null, null, null, null]
needs help on this.
thank you.
and wondering why i can read .txt file and not .doc. need advise on this as well.
import java.awt.List;
import java.io.*;
import java.util.ArrayList;
import javax.imageio.IIOException;
import javax.swing.JFileChooser;
public class searchforCapitalLetter {
public static void main(String[] args) throws IOException{
try {
// file chooser
JFileChooser chooser=new JFileChooser();
int returnVal = chooser.showOpenDialog(null);{
if(returnVal == JFileChooser.APPROVE_OPTION)
{ File f = chooser.getSelectedFile();}
FileInputStream fin = new FileInputStream(chooser.getSelectedFile());
DataInputStream din = new DataInputStream(fin);
BufferedReader br = new BufferedReader(new InputStreamReader(din));
ArrayList<String>list =new ArrayList<String> ();
if ((br.readLine()) != null) {
while (br.readLine() != " ") {
list.add(br.readLine());
System.out.print (list);
} br.close() ;
}//closes if statement
} // closes method dialog
} // closes try method
catch (FileNotFoundException e) {
e.printStackTrace();
} // closes catch method
} // closes method body
} // closes class method
Per the bufferedreader api:
public String readLine()
throws IOException
Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a
carriage return ('\r'), or a carriage return followed immediately by a
linefeed.
Returns: A String containing the contents of the line, not including
any line-termination characters, or null if the end of the stream has
been reached
Throws: IOException - If an I/O error occurs
Note that your code is making a few errors:
1) it is calling readline() once to check a return value and again to use the return value. The first call (in the while condition) removes the current value from the buffer, so your are dropping every other line.
2) you are using the wrong comparison to see if there's data remaining. x != y, where both x and y are objects, checks for pointer equality - is the memroy location where x is allocated the same as the memory location where y is allocated. what you really want is to store the value in a variable.
For example:
BufferedReader in = ...;
String s = in.readLine();
while(s!=null){
...
s = in.readLine();
}
The reason you can't use .doc is because .doc files are formatted, and as such, have some things your code would have to parse to read from them.
As far as the weird printing goes, you read the code twice before you even get to printing it (each time you call .readLine, it moves the scanner to the next line). Try the following code:
ArrayList<String>list =new ArrayList<String> ();
String currentLine;
while ((currentLine = br.readLine()) != null) {
list.add(currentLine);
System.out.println(currentLine);
} br.close() ;
}
That will keep track of the current line in a variable, rather than repeatedly moving the scanner to the next line. The other issue was it will be null, not " ", when the end of the file is reached
A classic BufferedReader to read content from a file.
this our file to read with Java:
This is the content to write into file
This is the content to write into file
package com.stackoverflow;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile{
private static final String FILENAME = "D:\\test\\filename.txt";
public static void main(String[] args) {
BufferedReader br = null;
FileReader fr = null;
try {
fr = new FileReader(FILENAME);
br = new BufferedReader(fr);
String sCurrentLine;
br = new BufferedReader(new FileReader(FILENAME));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Output :
This is the content to write into file
This is the content to write into file
Related
It couldnt replace the new word and place it in a new file.
I want to create a method that take 4 parameters, one with oldfile , one with new file, one with old word and one with new word and they are all of type string.
I also want to make it so that he case of the first letter the oldWord should be maintained when writing to the in the newFile, e.g. if oldWord was “Hit” and newWord was “Cab” then if “Hit” is found in the oldFile then “Cab” should be written to the newFile.
Im not allowed to use advanced java stuff like hashkeys and all that. Hope that enough infomaton and thank you in advance.
My code couldnt print the new words into the new file instead it just prints 4 more lines of the new words in the old file.
//////
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class part2d {
public static void main(String[] args)
{
modifyFile("test.txt","modify.txt", "Hit", "Cab");
System.out.println("done");
}
static void modifyFile(String oldfile, String newfile, String oldString, String newString)
{
File fileToBeModified = new File("modify.txt");
String oldContent = "";
BufferedReader reader = null;
FileWriter writer = null;
try
{
reader = new BufferedReader(new FileReader(fileToBeModified));
String line = reader.readLine();
while (line != null)
{
oldContent = oldContent + line + System.lineSeparator();
line = reader.readLine();
}
String newContent = oldContent.replaceAll(oldString, newString);
writer = new FileWriter(fileToBeModified,true);
writer.write(newContent);
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
reader.close();
writer.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
Both your reader and your writer are using the fileToBeModified variable. This variable is being set to modify.txt statically for both, so you're not actually reading and writing a new file, instead you're reading then appending the same file content again.
Think about what file you're creating using the BufferedReader/FileReader and the FileWriter, and consider how these are being set.
I read two files from different paths and while reading unable to write second file contents inside while loop, it is forcing me to initialize the variable which rt in below program. Please help me how to fix it to get
expected output. Thanks in advance..!!
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class ReadingFiles
{
public static void main(String[] args) throws IOException
{
String inp = "location\\first.txt";
String two = "location\\second.txt";
BufferedReader br = new BufferedReader(new FileReader(inp));
BufferedReader br2 = new BufferedReader(new FileReader(two));
String st,rt;
BufferedWriter bw = new BufferedWriter(new FileWriter("location"));
while((st=br.readLine())!= null || (rt=br2.readLine())!= null )
{
bw.write(st);
bw.newLine();
/*bw.write(rt);
bw.newLine();
System.out.println(rt);*/
//instance variable rt of type String is forcing me to initialize like
//for local variable and throwing nullpointer exception instead of fetching
//second file contents
}
bw.close();
}
}
Please find my program above, i am trying to write two text files contents
into third file. And the sample input and output given below
input
in file-1 a1a1a1
b2b2b2
c3c3c3
in file-2 d1d1d1
e2e2e2
f3f3f3
output
a1a1a1
d1d1d1
b2b2b2
e2e2e2
c3c3c3
f3f3f3
There is several mistakes you have done in the code and also there are better ways to implement the code.
But for your understatement i will update your existing code.
1) st and rt should be initialized. because when first time st is initializing rt is not yet initialized.
2) || should be &&. because you need to loop until all the files are finished reading.
3) st & rt should be checked if it's null or not.
please check following code .
public class ReadingFiles
{
public static void main(String[] args) throws IOException
{
String inp = "first.txt";
String two = "second.txt";
BufferedReader br = new BufferedReader(new FileReader(inp));
BufferedReader br2 = new BufferedReader(new FileReader(two));
String st,rt="";
BufferedWriter bw = new BufferedWriter(new FileWriter("location"));
boolean isCompleted = false;
while( !isCompleted)
{
st=br.readLine() ;
bw.write(st==null?"":st);
bw.newLine();
rt=br2.readLine();
bw.write(rt==null?"":rt);
bw.newLine();
isCompleted = (st==null && rt == null) ? true : false ;
}
bw.close();
}
}
I would do this with an infinite do while loop instead of while and manage the loop exit condition in a seperate if inside my loop.
Why? Because the second conditional statement in your while header may not be executed since it is an or (||) and the compiler ignores the rest of your conditional statement when the first statement istrue and therefore rtnever get initiated. Thats why the compiler is forcing you to initialize rt.
You aren't closing your readers, and I would prefer the try-with-resources over explicit closes. Then, read each line from your respective files in an infinite loop. Test for null from each file individually before writing to the output buffer, and again at the end to terminate your loop when you have exhausted both inputs. Something like,
try (BufferedReader br = new BufferedReader(new FileReader(inp));
BufferedReader br2 = new BufferedReader(new FileReader(two));
BufferedWriter bw = new BufferedWriter(new FileWriter("location"))) {
while (true) {
String st = br.readLine();
if (st != null) {
bw.write(st);
bw.newLine();
}
String rt = br2.readLine();
if (rt != null) {
bw.write(rt);
bw.newLine();
}
if (st == null && rt == null) {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
I am working on a program that evaluates lisp expressions using a stack implemented by either an array or linked list. I need to read the file in from the first line from right to left. Currently I am reading it in from left to right but I do not understand how I can switch it around. Any help you can give me is greatly appreciated! Thank you!
**I know the program is nowhere near complete, I just need to accomplish this before I can continue.
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.*;
import java.io.BufferedReader;
public class A2Q5{
private static Scanner in;
public static void main (String [] args)
{
if(args.length != 2) {
System.out.println("Please execute as: java A2Q5 type infile");
}
BoundedStack<Double> stack;
if(args[0].equals("0"))
stack = new BSArray<Double>(20);
else
stack = new BSLinkedList<Double>();
// The name of the file to open.
String fileName = args[1];
// This will reference one line at a time
//char c = null;
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
for (int i = line.length() - 1; i >= 0; i--){
line.charAt(i);
System.out.println(line.charAt(i));
}
}
}
catch(FileNotFoundException ex) {
System.out.println("Unable to open file " + fileName);
}
catch(IOException ex) {
System.out.println("Error reading file " + fileName);
}
}
}
Drop the use of FileInputStream and use BufferedReader that you already prepared but never use. Use its method readLine to read info from your file line by line. Once you got an individual line you can iterate through it character by character from the end of the String to its beginning. This is exactly what you want.
If I have something like this in my code:
String line = r.readLine(); //Where r is a bufferedReader
How can I avoid a crash if the next line is the end of the file? (i.e. null)
I need to read the next line because there may be something there that I need to deal with but if there isn't the code just crashes.
If there is something there then all is OK, but I can't be guaranteed that there will be something there.
So if I do something like: (pseudo code):
if (r.readLine is null)
//End code
else {check line again and excecute code depending on what the next line is}
The issue I have with something like this is, that when I check the line against null, it already moves onto the next line, so how can I check it again?
I've not worked out a way to do this - any suggestions would be a great help.
Am... You can simply use such a construction:
String line;
while ((line = r.readLine()) != null) {
// do your stuff...
}
If you want loop through all lines use that:
while((line=br.readLine())!=null){
System.out.println(line);
}
br.close();
You can use the following to check for the end of file.
public bool isEOF(BufferedReader br)
{
boolean result;
try
{
result = br.ready();
}
catch (IOException e)
{
System.err.println(e);
}
return result;
}
In your case you can read the next line because there may be something there.If there isn't anything, your code won't crash.
String line = r.readLine();
while(line!=null){
System.out.println(line);
line = r.readLine();
}
A question in the first place, why don't you use "Functional Programming Approach"? Anyways, A new method lines() has been added since Java 1.8, it lets BufferedReader returns content as Stream. It gets all the lines from the file as a stream, then you can sort the string based on your logic and then collect the same in a list/set and write to the output file. If you use the same approach, there is no need to get worried about NullPointerException. Below is the code snippet for the same:-
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;
public class LineOperation {
public static void main(String[] args) throws IOException {
Files.newBufferedReader(Paths.get("C://xyz.txt")).
lines().
collect(Collectors.toSet()). // You can also use list or any other Collection
forEach(System.out::println);
}
}
You can do it via BufferReader. I know this is not relevant to following question. But I would post it for extra fact for a newbie who would not use BufferReader but Scanner for reading file.
A part from BufferReader you could use Java Scanner class to read the file and check the last line.
Buffer Reader
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
// process the line
}
}
Scanner
try {
Scanner scanner = new Scanner(new FileReader(file));
while (scanner.hasNext()) {
// Above checks whether it has or not ....
}
} catch (IOException e) {
e.printStackTrace();
}
If you use this code fragment in a multi threaded environment, go ahead with BufferReader since its synchronized.
In addition, BufferReader is faster than Scanner.
If you would like to do some check like:
if (reader.ready())
stringBuilder.append("#");
You can use ready()
public static void check() throws IOException {
InputStream in = new FileInputStream(new File(filePath));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
if (reader.ready())
stringBuilder.append("#");
}
String returnedString = stringBuilder.toString();
System.out.println(returnedString);
}
You could purposely have it throw the error inside your loop. i.e.:
String s = "";
while (true) {
try {
s = r.readline();
}catch(NullPointerException e) {
r.close();
break;
}
//Do stuff with line
}
what everyone else has sad should also work.
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.