dear all here i have this code:
File file = new File("flowers_petal.txt");
Scanner in = new Scanner(file);
while(in.hasNext()){
String line = in.nextLine();
System.out.println(line);
I want to read from a file and print each line, but this code doesn't work because of some exceptions (throw exception??), how can i put it in a way that it would read from the flowers.txt file, which is on my desktop and will print each line from this file in the console?
Recheck your code
File file = new File("flowers_petal.txt"); // This is not your desktop location.. You are probably getting FileNotFoundException. Put Absolute path of the file here..
while(in.hasNext()){ // checking if a "space" delimited String exists in the file
String line = in.nextLine(); // reading an entire line (of space delimited Strings)
System.out.println(line);
SideNote : use FileReader + BufferedReader for "reading" a file. Use Scanner for parsing a file..
Here you go.. Full code sample. Assuming you put you file in C:\some_folder
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileReader {
public static void main(String args[]) {
File file = new File("C:\\some_folder\\flowers_petal.txt");
Scanner in;
try {
in = new Scanner(file);
while (in.hasNext()) {
String line = in.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
You are checking for the wrong condition, you need to check for hasNextline() instead of hasNext(). So the loop will be
while(in.hasNextLine()){
String line = in.nextLine();
System.out.println(line);
}
Consider these 2 points :
the current location you are giving in your file is not valid (if
your .java (source) file is not on Desktop), so give the full path
for your file.
the new Scanner(File file) throws FileNotFoundException, so you have to put the code in try-catch block or just use throws.
Your code may look like this :
try {
File file = new File("path_to_Desktop/flowers_petal.txt");
Scanner in = new Scanner(file);
while(in.hasNextLine()){
String line = in.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e){
e.printStackTrace();
}
try this
public static void main(String[] args) throws FileNotFoundException {
//If your java file is in the same directory as the text file
//then no need to specify the full path ,You can just write
//File file = new File("flowers_petal.txt");
File file = new File("/home/ashok/Desktop/flowers_petal.txt");
Scanner in = new Scanner(file);
while(in.hasNext()){
System.out.println(in.nextLine());
}
in.close();
}
NOTE :I am using linux ,If you are using windows your desktop path would be different
Try this................
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt")))
{
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
give your exact path in the FileReader("exact path must be here...")
source: http://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/
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.
So I'm having a few troubles here. I need to be able to write my output to a file, and have it contain only the keywords specified in the code. This code is writing nothing to the file, and it only opens another box for user input. How do I get it to close the input box after the user inputs the file name, get it to write the output to the file, and get the output to display in the compiler? Thanks!
import java.util.*;
import java.io.*;
public class Classname {
static Scanner sc = new Scanner(System.in);
public static void main(String args[]) throws IOException,
FileNotFoundException {
String filename;
// Connecting to a file with a buffer
PrintWriter outFile = new PrintWriter(
new BufferedWriter(
new FileWriter("chatOutput.log")));
// Get the file
System.out.print("Please enter full name of the file: ");
filename = sc.next();
// Assign the name of the text file to a file object
File log = new File( filename);
String textLine = null; // Null
String outLine = ""; // Null
while(sc.hasNext())
{
String line=sc.nextLine();
if(line.contains("LANTALK"))
System.out.println(line);
}
try
{
// assigns the file to a filereader object..this will throw an error if
the file does not exist or cannot be found
BufferedReader infile = new BufferedReader(new FileReader(log));
try
{
// read data from a file..this will throw and error if something goes
wrong reading (empty or past end of file)
while((textLine = infile.readLine()) != null)
{
//System.out.printf("%s\n",textLine);
outLine = textLine.toUpperCase();
outFile.printf("%s\n",outLine);
}// end of while
} // end of try
finally // finally blocks get executed even if an exception is thrown
{
infile.close();
outFile.close();
}
}// end of try
catch (FileNotFoundException nf) // this goes with the first try because it
will throw a FileNotFound exception
{
System.out.println("The file \""+log+"\" was not found");
}
catch (IOException ioex) // this goes with the second try because it will
throw an IOexception
{
System.out.println("Error reading the file");
}
} /// end of main
} // end of class
What you need is to end the while(sc.hasNext()) while loop because the Scanner sc will always have a next because you are literally saying asking yourself if you got the line from the user then wait for next line with sc.nextLine(); then you are putting it into a string so next time you ask yourself do i have the line the answer is yes,anyways it's a little complicated to get over this issue you need to change the while loop to have a special word that will brake it,so you have to change it from:
while(sc.hasNext()){
String line=sc.nextLine();
if(line.contains("LANTALK"))
System.out.println(line);
}
To,for example:
while(true){
String line=sc.nextLine();
if(line.contains("LANTALK"))
System.out.println(line);
if(line.contains("END"))
break;
}
Also you need to check if the file entered by the user exists and actually add the text from the console to the file,so it would look something like this:
if(!log.exists())log.createNewFile();
// Connecting to a file with a buffer
PrintWriter logFile = new PrintWriter(
new BufferedWriter(
new FileWriter(log.getAbsolutePath())));
while(true){
String line=sc.nextLine();
if(line.contains("LANTALK"))
System.out.println(line);
if(line.contains("END"))
break;
logFile.println(line);
}
logFile.close();
Now all we have to do is print the output to the console when writing it to the logFile,so the while((textLine = infile.readLine()) != null),will now look a little something like this:
while((textLine = infile.readLine()) != null)
{
//System.out.printf("%s\n",textLine);
outLine = textLine.toUpperCase();
outFile.println(outLine);
System.out.println(outLine);
}// end of while
} // end of try
So in the end the hole thing should look a little something like this:
import java.util.*;
import java.io.*;
public class Classname{
static Scanner sc = new Scanner(System.in);
public static void main(String args[]) throws IOException,
FileNotFoundException {
String filename;
// Connecting to a file with a buffer
PrintWriter outFile = new PrintWriter(
new BufferedWriter(
new FileWriter("chatOutput.log")));
// Get the file
System.out.print("Please enter full name of the file: ");
filename = sc.next();
// Assign the name of the text file to a file object
File log = new File(filename);
String textLine = null; // Null
String outLine = ""; // Null
if(!log.exists())log.createNewFile();
// Connecting to a file with a buffer
PrintWriter logFile = new PrintWriter(
new BufferedWriter(
new FileWriter(log.getAbsolutePath())));
while(true){
String line=sc.nextLine();
if(line.contains("LANTALK"))
System.out.println(line);
if(line.contains("END"))
break;
logFile.println(line);
}
logFile.close();
try{
// assigns the file to a filereader object..this will throw an error if the file does not exist or cannot be found
BufferedReader infile = new BufferedReader(new FileReader(log));
try
{
// read data from a file..this will throw and error if something goes wrong reading (empty or past end of file)
while((textLine = infile.readLine()) != null)
{
//System.out.printf("%s\n",textLine);
outLine = textLine.toUpperCase();
outFile.println(outLine);
System.out.println(outLine);
}// end of while
} // end of try
finally // finally blocks get executed even if an exception is thrown
{
infile.close();
outFile.close();
}
}// end of try
catch (FileNotFoundException nf) // this goes with the first try because it will throw a FileNotFound exception
{
System.out.println("The file \""+log+"\" was not found");
}
catch (IOException ioex) // this goes with the second try because it will throw an IOexception
{
System.out.println("Error reading the file");
}
} /// end of main
} // end of class
If this is not what you are looking for i'm sorry,but i tried to make it do want you described you wanted,i mean it does write the output to the file, and get the output to display in the compiler,here's what the compiler console looks like:
Please enter full name of the file: test.txt
hi
hi
hi
END
HI
HI
HI
I'm sorry if this is not what you wanted but i tried my best,hope it helps.
Alright so I have a very small program I'm working on designed to take the contents of a text file, test.txt, and put them in another empty file testCopied.txt . The trick is that I want to use Scanner and printWriter as I am trying to understand these a bit better.
Here is what my code looks like:
import java.io.*;
import java.util.*;
public class CopyA
{
public static void main(String [] args)
{
String Input_filename = args[0];
String Output_filename = args[1];
char r = args[2].charAt(0);
try
{
Scanner sc = new Scanner(new File(Input_filename));
FileWriter fw = new FileWriter(Output_filename);
PrintWriter printer = new PrintWriter(fw);
while(sc.hasNextLine())
{
String s = sc.nextLine();
printer.write(s);
}
sc.close();
}
catch(IOException ioe)
{
System.out.println(ioe);
}
}
}
This compiles, but when I look at testCopied.txt it is still blank, and hasn't had test.txt's content transferred to it. What am I doing wrong? Java IO is pretty confusing to me, so I'm trying to get a better grasp on it. Any help is really appreciated!
You have missed out flush() and close() for the PrintWriter object which you need to add
and then use the line separator using System.getProperty("line.separator") while writing each line into second file.
You can refer the below code:
PrintWriter printer = null;
Scanner sc = null;
try
{
String lineSeparator = System.getProperty("line.separator");
sc = new Scanner(new File(Input_filename));
FileWriter fw = new FileWriter(Output_filename);
printer = new PrintWriter(fw);
while(sc.hasNextLine())
{
String s = sc.nextLine()+lineSeparator; //Add line separator
printer.write(s);
}
}
catch(IOException ioe)
{
System.out.println(ioe);
} finally {
if(sc != null) {
sc.close();
}
if(printer != null) {
printer.flush();
printer.close();
}
}
Also, ensure that you are always closing resources in the finally block (which you have missed out for Scanner object in your code).
I want to go to command line and type the input, so the BufferReader can have access to the file. How am i supposed to do that ?
The input will be "java TagMatching path_to_html_file.html"
// Importing only the classes we need
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TagMatching {
public static void main(String[] args) {
BufferedReader br = null;
// try to read the file
try {
br = new BufferedReader(new FileReader(**/*DONT KNOW WHAT TO DO*/**));
String line;
} catch (IOException e) {
e.printStackTrace();
}
}
}
The input will be java TagMatching path_to_html_file.html
After the name of the app (TagMatching) you find the arguments (path_to_html_file.html) this are the String[] args of the main method, so just use them, in this case args[0]:
public static void main(String[] args) {
BufferedReader br = null;
// try to read the file
try {
// check if there are some arguments
if (null != args[0] &&
// lenght > 5 because a.html will be shortest filename
args[0].lenght > 5 &&
// check if arguments have the correct file extension
args[0].endsWith(".html"))
{
br = new BufferedReader(new FileReader(args[0]));
// do more stuff
}
} catch (IOException e) {
e.printStackTrace();
}
}
To get the input from the console you have to use Scanner like this;
Scanner in = new Scanner(System.in);
System.out.println("Enter file path");
String s = in.nextLine(); //C:\\testing.txt
And to use that file path in the FIleReader use like this;
br = new BufferedReader(new FileReader(s));
Exactly works with args[0].
So,br = new BufferedReader(new FileReader(args[0])); will act as the questioner intends
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.