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.
Related
I have tried to implement a simple program to delete a particular text from a file, some how it is not able to delete it. I am reading entire file content into a temp file , delete the user input string from it and update the content to the original file.
Any help would be highly appreciated.
public class TextEraser{
public static void main(String[] args) throws IOException {
System.out.print("Enter a string to remove : ");
Scanner scanner = new Scanner(System. in);
String inputString = scanner. nextLine();
// Locate the file
File file = new File("/Users/lobsang/documents/input.txt");
//create temporary file
File temp = File.createTempFile("file", ".txt", file.getParentFile());
String charset = "UTF-8";
try {
// Create a buffered reader
// to read each line from a file.
BufferedReader in = new BufferedReader(new FileReader(file));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));
String s = in.readLine();
// Read each line from the file and echo it to the screen.
while (s !=null) {
s=s.replace(inputString,"");
s = in.readLine();
}
writer.println(s);
// Close the buffered reader
in.close();
writer.close();
file.delete();
temp.renameTo(file);
} catch (FileNotFoundException e1) {
// If this file does not exist
System.err.println("File not found: " + file);
}
}
After replace with input string, write string immediate in file.
while (s != null) {
s = s.replace(inputString, "");
writer.write(s);
// writer.newLine();
s = in.readLine();
}
For new line , use BufferedWriter in place of PrintWriter, it contains method newLine()
writer.newLine();
Remove this
writer.println(s);
I need to read from one text file(carsAndBikes.txt) and the write in either cars.txt or bikes.txt
carsAndBikes contains a list of cars and bikes and the first character of each name is C or B (C for Car and B for Bike). So far i have that but its showing cars and bikes content. Instead of the separated content.(CARS ONLY OR BIKES ONLY)
public static void separateCarsAndBikes(String filename) throws FileNotFoundException, IOException
{
//complete the body of this method to create two text files
//cars.txt will contain only cars
//bikes.txt will contain only bikes
File fr = new File("C:\\Users\\KM\\Documents\\NetBeansProjects\\Question4\\carsAndBikes.txt");
Scanner scanFile = new Scanner(fr);
String line;
while(scanFile.hasNextLine())
{
line = scanFile.nextLine();
if(line.startsWith("C"))
{
try(PrintWriter printWriter = new PrintWriter("C:\\Users\\KM\\Documents\\NetBeansProjects\\Question4\\cars.txt"))
{
printWriter.write(line);
}
catch(Exception e)
{
System.out.println("Message" + e);
}
}
else
{
try(PrintWriter printWriter = new PrintWriter("C:\\Users\\KM\\Documents\\NetBeansProjects\\Question4\\bikes.txt"))
{
printWriter.write(line);
}
catch(Exception e)
{
System.out.println("Message" + e);
}
}
}
//close the file
scanFile.close();
}
You're checking if the input filename starts with a c instead of checking if the line read starts with a c.
You should also open both your output files before your loop, and close them both after the loop.
// Open input file for reading
File file = new File("C:\\Users\\KM\\Documents\\NetBeansProjects\\Question4\\carsAndBikes.txt");
BufferedReader br = new BufferedReader(new FileReader(file)));
// Open bike outputfile for writing
// Open cars outputfile for writing
// loop over input file contents
String line;
while( line = br.readLine()) != null ) {
// check the start of line for the character
if (line.startsWith("C") {
// write to cars
} else {
// write to bikes
}
}
// close all files
I want to add a functionality in the App where the user can change machine IP scheme (IP, SubnetMask, DefaultGateway) permanently, So I want to do Read/Write operation on the Linux Network Configuration File ("/etc/network/interfaces") using following code.
File file = new File("/etc/network/interfaces");
boolean exists = file.exists();
String line = "";
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
try
{
FileReader fr = new FileReader(file.getAbsoluteFile());
//BufferedReader br = new BufferedReader(fr);
Scanner scan = new Scanner(new FileInputStream(file));
if(exists)
{
while(scan.hasNext()) //while((line = br.readLine()) != null)
{
// Any Write operation
}
scan.close(); // br.close
}
}
bw.close();
Problem is that the check on while() loop keeps returning false.
I did some research for any alternative for that which includes using BufferedReader or Scanner to read the file but didn't work. All the following checks just keep returning false.
while(scan.hasNext())
while(scan.hasNextLine())
while((line = br.readLine()) != null)
Although file does exist, it contains its content But every time I try to read it with the above code all file content gets removed and the file gets empty.
Am I missing something? Is there any better alternative? I've also tried reading another file in the same directory which has full permission of read/write/execute for all users but still same result
As I'm trying to open the file to write and read was what causing the issue and loop gets terminated in the beginning. So it turns out that You should not use FileWriter before FileReader for same file. Doing so at the same time causing File reader to read empty file and loop terminates as it gets EndOfFile right at the beginning. Afterwards it closes the file empty hence all its contents are being lost.
Better way was to
First open the file for 'Read' only.
Scan through file line by line & keep a buffer of each line parsed (List in my case).
Add the content you wish to update in the file when you get to your Marker line & update you buffer as well.
Now open the file to 'Write' you updated list on it
Note: This is suitable if the file size is reasonably small to accommodate the file processing time.
File file = new File("/etc/network/interfaces");
boolean exists = file.exists();
Scanner scanner = null;
PrintWriter wirtter = null;
String line = "";
List<String> fileLines = new ArrayList<String>();
if(exists)
{
try {
scanner = new Scanner(new FileInputStream(file));
while(scanner.hasNextLine())
{
line = scanner.nextLine();
fileLines.add(line);
if(line.trim().startsWith("iface eth0 inet static"))
{
while(scanner.hasNextLine())
{
line = scanner.nextLine();
fileLines.add(line);
if(line.trim().startsWith("address"))
{
String updateStr = "\taddress "+ipAddress+"\t";
fileLines.remove(fileLines.size()-1);
fileLines.add(updateStr);
System.out.println("IP add updated");
}
else if(line.trim().startsWith("netmask"))
{
String updateStr = "\tnetmask "+subnetMask+"\t";
fileLines.remove(fileLines.size()-1);
fileLines.add(updateStr);
System.out.println("subnet add updated");
}
else if(line.trim().startsWith("gateway"))
{
String updateStr = "\tgateway "+defaultGateway+"\t";
fileLines.remove(fileLines.size()-1);
fileLines.add(updateStr);
System.out.println("Gatway add updated");
}
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
finally{
if(scanner != null)
scanner.close();
}
Now do the Writing Separately. And Also you'd want to restart the networking service
try {
wirtter = new PrintWriter(file);
for (String lineW : fileLines)
wirtter.println(lineW);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
finally{
if(wirtter != null)
wirtter.close();
}
}
synchronized (p) {
String cmd = "sudo /etc/init.d/networking restart ";
p.exec(cmd);
p.wait(10000);
System.out.println("finishing restart 'Networking:' service");
}
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/
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.