I have tried many times to read a user input and then write it to a file but I haven't find a solution. Here is my code...
The main class.
import java.util.HashMap;
import java.util.Scanner;
public class cShell{
static String Currentpath="C:\\";
public String Current = Currentpath;
static HashMap<String, ICommand> myhashData=new HashMap<String, ICommand>();
public static void main(String[] args)
{
myhashData.put("ltf", new cITF());
myhashData.put("nbc", new cNBC());
myhashData.put("gdb", new cGDB());
myhashData.put("Tedit", new cTedit());
String Input = "";
do{
System.out.print(Currentpath+"> ");
//String Input = "";
Scanner scan = new Scanner(System.in);
if(scan.hasNext()){
Input = scan.nextLine().trim();
}
if(Input.equals("exit")){
System.exit(0);
}
if(myhashData.containsKey(Input)){
ICommand myCommand=myhashData.get(Input);
myCommand.Execute();
}
else{
System.out.println("Invalid Command");
}
}while(!Input.equals("exit"));
}
}
This is the class that do the read and write.
import java.util.*;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
//import java.lang.System.*;
public class cTedit implements ICommand{
#Override
public void Execute() {
String filename = "";
System.out.println("Enter the file name to be edited");
Scanner scan = new Scanner(System.in);
if(scan.hasNext()){
filename = scan.nextLine();
}
String line = null;
try{
InputStreamReader ISR = new InputStreamReader(System.in);
//FileReader fileReader = new FileReader(ISR);
FileWriter fileWriter = new FileWriter(cShell.Currentpath+"\\"+filename);
BufferedReader bufferedReader = new BufferedReader(ISR);
System.out.println("Enter text into the file");
while((line = bufferedReader.readLine()) != null){
fileWriter.write(line);
}
bufferedReader.close();
}catch(FileNotFoundException ex){
System.out.println("Unable to open file '" + filename + "'");
}
catch(IOException ex){
System.out.println("Error reading file '" + filename + "'");
}
}
}
My problem is when I enter some text as user input, pressing enter doesn't stop me from entering inputs, but when I press Ctrl+z it ran into an infinite loop.
Try this one in cTedit class.
bufferedReader.readLine() will never return null in your case.
Type exit to come out of loop.
while((line = bufferedReader.readLine()) != null){
if(line.equals("exit")){
break;
}
fileWriter.write(line);
}
Use fileWriter.close() in the end.
Maybe that's not the source of your problem, but I don't think that you need to check the hasnext() condition to read a line :
if(scan.hasNext()){
filename = scan.nextLine();
}
just filename = scan.nextLine(); should be enough.
Use the following
if(Input.equals("exit") || Input.equals("")){
System.exit(0);
}
instead of
if(Input.equals("exit")){
System.exit(0);
}
In order to close the fileWriter after just before exiting add a method closeFile as below.
import java.util.;
import java.io.;
import java.nio.file.Files;
import java.nio.file.Path;
//import java.lang.System.*;
public class cTedit implements ICommand{
private FileWriter fileWriter;
#Override
public void Execute() {
// TODO Auto-generated method stub
String filename = "";
System.out.println("Enter the file name to be edited");
Scanner scan = new Scanner(System.in);
if(scan.hasNext()){
filename = scan.nextLine();
}
String line = null;
try{
InputStreamReader ISR = new InputStreamReader(System.in);
//FileReader fileReader = new FileReader(ISR);
fileWriter = new FileWriter(cShell.Currentpath+"\\"+filename);
BufferedReader bufferedReader = new BufferedReader(ISR);
System.out.println("Enter text into the file");
while((line = bufferedReader.readLine()) != null){
fileWriter.write(line);
}
bufferedReader.close();
}catch(FileNotFoundException ex){
System.out.println("Unable to open file '" + filename + "'");
}
catch(IOException ex){
System.out.println("Error reading file '" + filename + "'");
} finally {
fileWriter.close();
}
}
public void closeFile() {
fileWriter.close();
}
}
and then callCloseFile in cShell class just before exiting
Related
How to read from a file strings or numbers with one space between them.
You can just write a class which will read a file and remove the spaces.
package com.example.removespaces
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class RemoveSpacesInFileEx {
public static void main(String[] args) throws FileNotFoundException, IOException {
FileReader fr = new FileReader("input.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("outfile.txt");
String line;
while((line = br.readLine()) != null)
{
line = line.trim();
line=line.replaceAll("\\s+", " ");
fw.write(line);
}
fr.close();
fw.close();
}
}
public void readData() {
File file = new File("file.txt"); //You can put your file name or your file position here
try {
Scanner sc = new Scanner(file);
while(sc.hasNext()) {
System.out.println(sc.nextLine());
} System.out.println();
}
catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
System.out.println("End of the Main");
} //This will read it from a file and print on your console
I'm sort of new to Java and I'm learning about input validation methods but I'm struggling with an assignment that I'm trying to complete. Can someone help me? The following code is reading a file somewhere on your computer. I'm supposed to verify that the file path is correct with an input validation method. This is what I have so far:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class readFile {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the name of your File: ");
String fileName = scan.nextLine();
File inputFile = new File(fileName);
BufferedReader reader = null;
try {
String sCurrentLine;
reader = new BufferedReader(new FileReader(inputFile));
while ((sCurrentLine = reader.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
System.out.print(e.getMessage());
} finally {
try {
if (reader != null)reader.close();
} catch (IOException ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
}
}
The easiest way to tell if the file path given is correct is to simply check if it exists:
if (inputFile.exists() && !inputFile.isDirectory()) {
// inputFile has a valid path.
}
Use following code checking.
File f = new File(filePathString);
if(f.exists() && !f.isDirectory()) {
// do something
}
I'm writing a code where in data in a file has to be replaced with another file content.
I know how to use a string Replace() function. but the problem here is, I want to replace a string with a entirely new Data.
I'm able to append(in private static void writeDataofFootnotes(File temp, File fout)) the content, but unable to know how do I replace it.
Below is my code.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
public class BottomContent {
public static void main(String[] args) throws Exception {
String input = "C:/Users/u0138039/Desktop/Proview/TEST/Test/src.html";
String fileName = input.substring(input.lastIndexOf("/") + 1);
URL url = new URL("file:///" + input);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
File fout = new File("C:/Users/u0138039/Desktop/TEST/Test/OP/" + fileName);
File temp = new File("C:/Users/u0138039/Desktop/TEST/Test/OP/temp.txt");
if (!fout.exists()) {
fout.createNewFile();
}
if (!temp.exists()) {
temp.createNewFile();
}
FileOutputStream fos = new FileOutputStream(fout);
FileOutputStream tempOs = new FileOutputStream(temp);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
BufferedWriter tempWriter = new BufferedWriter(new OutputStreamWriter(tempOs));
String inputLine;
String footContent = null;
int i = 0;
while ((inputLine = in.readLine()) != null) {
if (inputLine.contains("class=\"para\" id=\"")) {
footContent = inputLine.replaceAll(
"<p class=\"para\" id=\"(.*)_(.*)\" style=\"text-indent: (.*)%;\">(.*)(.)(.*)</p>",
"<div class=\"tr_footnote\">\n<div class=\"footnote\">\n<sup><a name=\"ftn.$2\" href=\"#f$2\" class=\"tr_ftn\">$4</a></sup>\n"
+ "<div class=\"para\">" + "$6" + "\n</div>\n</div>\n</div>");
inputLine = inputLine.replaceAll(
"<p class=\"para\" id=\"(.*)_(.*)\" style=\"text-indent: (.*)%;\">(.*)(.)(.*)</p>",
"");
tempWriter.write(footContent);
tempWriter.newLine();
}
inputLine = inputLine.replace("</body>", "<hr/></body>");
bw.write(inputLine);
bw.newLine();
}
tempWriter.close();
bw.close();
in.close();
writeDataofFootnotes(temp, fout);
}
private static void writeDataofFootnotes(File temp, File fout) throws IOException {
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader(temp);
fw = new FileWriter(fout, true);
int c = fr.read();
while (c != -1) {
fw.write(c);
c = fr.read();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
close(fr);
close(fw);
}
}
public static void close(Closeable stream) {
try {
if (stream != null) {
stream.close();
}
} catch (IOException e) {
// ...
}
}
}
Here I'm searching for a particular string and saving it in a separate txt file. And once I'm done with the job. I want to replace the <hr /> tag with the entire txt file data.
How can I achieve this?
I'd modify your processing loop as follows:
while ((inputLine = in.readLine()) != null) {
// Stop translation when we reach end of document.
if (inputLine.contains("</body>") {
break;
}
if (inputLine.contains("class=\"para\" id=\"")) {
// No changes in this block
}
bw.write(inputLine);
bw.newLine();
}
// Close temporary file
tempWriter.close();
// Open temporary file, and copy verbatim to output
BufferedReader temp_in = Files.newBufferedReader(temp.toPath());
String footnotes;
while ((footnotes = temp_in.readLine()) != null) {
bw.write(footnotes);
bw.newLine();
}
temp_in.close();
// Finish document
bw.write(inputLine);
bw.newLine();
while ((inputLine = in.readLine()) != null) {
bw.write(inputLine);
bw.newLine();
}
// ... and close all open files
I can't resolve my problem on "server has added null."
It doesn't go to the menu first to process data.
This is also similar to writing client to server question.
Here's my codes:
Student:
import java.lang.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class Student {
public static void main(String args[]) {
PrintWriter out = null;
Scanner sc = new Scanner (System.in);
//initialization
String student = " ";
String id = " ";
String name = " ";
try {
Socket skt = new Socket("localhost", 1234);
out = new PrintWriter(skt.getOutputStream(), true);
while (name.equals("exit")) { //never ending menu
System.out.print("Please enter name: ");
name = sc.nextLine();
System.out.print("Please enter ID Number: ");
id = sc.nextLine();
student = name +" - "+ id;
out.print(student);
}
} catch(Exception e) {
System.out.println("Whoops! It didn't work.");
} finally {
if (out != null) {
try {
out.close();
} catch (Exception e) {
}
}
}
}
}
Server:
import java.lang.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class Server {
public static void main(String args[]) {
Scanner sc = new Scanner (System.in);
ArrayList<String> collector = new ArrayList<String>();
String x = "";
try {
ServerSocket srvr = new ServerSocket(1234);
Socket skt = srvr.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream()));
x = in.readLine();
collector.add(x);
System.out.println("Server has added "+collector.get(collector.size()-1));
}
catch(Exception e) {
e.printStackTrace();
System.out.print("Whoops! It didn't work!\n");
}
}
}
Any idea what's wrong?
According to the "never ending menu"-condition select == 2, your initialization of int select = 0; and no other writings to select you will never execute the code in the loop.
Your loop will never execute as you have set select = 0
Let's say I have the following code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class EditFile {
public static void main(String[] args) {
try{
String verify, putData;
File file = new File("file.txt");
file.createNewFile();
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Some text here for a reason");
bw.flush();
bw.close();
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while( br.readLine() != null ){
verify = br.readLine();
if(verify != null){
putData = verify.replaceAll("here", "there");
bw.write(putData);
}
}
br.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
All I wanted to do was to write something in a text file, in my case "Some text here for a reason". Then to read data from my file, and finally to change my text from my file from "Some text here for a reason" in "Some text there for a reason". I ran the code but all it happens is to write in my file "Some text here for a reason".
I tried to figure out what could be wrong in my code, but unfortunately it was in vain. Any advice or rewrite is highly appreciated from me.
Change your code to that:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class EditFile {
public static void main(String[] args) {
try{
String verify, putData;
File file = new File("file.txt");
file.createNewFile();
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Some text here for a reason");
bw.flush();
bw.close();
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while( (verify=br.readLine()) != null ){ //***editted
//**deleted**verify = br.readLine();**
if(verify != null){ //***edited
putData = verify.replaceAll("here", "there");
bw.write(putData);
}
}
br.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
The Problem is that you are calling br.readLine() twice which is provoking the application to read line1 and then line2 and in your case you have just one line which means that your program read it in the conditional form and when it comes to declaring it to the variable verify, it is stopping because you don't have anymore data to read your file.
I would do it this way:
import java.io.*;
public class EditFile {
public static void main(String[] args) {
try{
String verify, putData;
File file = new File("file.txt");
file.createNewFile();
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Some text here for a reason");
bw.flush();
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while( (verify=br.readLine()) != null )
{
if(verify != null)
{
putData = verify.replaceAll("here", "there");
bw.write(putData);
}
}
br.close();
bw.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
use this code, I used it to remove logs and System.out statements in java file.
just change the matching and replacing string.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class FileReplace {
List<String> lines = new ArrayList<String>();
String line = null;
Scanner scan = null;
public void doIt() {
scan = new Scanner(System.in);
while (true) {
try {
System.out
.println("enter qualified file name ex.D:\\shiv\\shiv android all\\Main work space\\Welcomescreen1.java");
String path = scan.nextLine();
File f1 = new File(path);
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
int i = 0;
while ((line = br.readLine()) != null) {
if (line.contains("System.out")) {
line = line.replace("System.out", "//");
} else if (line.contains("Log.")) {
line = line.replace("Log", "//");
}
lines.add(i, line);
i++;
}
fr.close();
br.close();
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
for (int j = 0; j < lines.size(); j++) {
System.out.println(j + "." + lines.get(j));
out.append(lines.get(j));
out.newLine();
}
out.flush();
out.close();
System.out
.println("====================work done===================");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public static void main(String args[]) {
FileReplace fr = new FileReplace();
fr.doIt();
}
}
import java.io.*;
public class TextFile
{
public static void main(String[] args)
{
try
{
String verify, putData;
File file = new File("G:\\Dairy.txt");
file.createNewFile();
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("I am Shah Khalid");
bw.flush();
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while( (verify=br.readLine()) != null )
{
if(verify != null)
{
putData = verify.replaceAll("here", "there");
//bw.write(putData);
}
}
br.close();
bw.close();
}
catch(IOException e)
{
e.printStackTrace();
}
System.out.println("Shah");
}
}
There is no need to type bw.write(putData);, because it will just print the statement twice.
Whatever you want in a file, just give the correct path of the file and use the above code accordingly.
File file = new File("/tmp/my.txt");
FileWriter fw;
BufferedReader br;
BufferedWriter bw;
boolean no=false;
String line;
String data="";
String lessonPath="my new line";
try {
if(!file.exists()){
fw = new FileWriter(file);
bw = new BufferedWriter(fw);
bw.write(lessonPath);
bw.flush();
bw.close();
}else{
br = new BufferedReader(new FileReader(file));
while((line =br.readLine()) !=null){
if(!no){
data=line;
no=true;
}else{
data = data+"\n"+line;
}
}
bw = new BufferedWriter(new FileWriter(file));
bw.write(data+"\n"+lessonPath);
bw.flush();
bw.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}