BufferedWriter without try method IOException - java

I know this topic has been discussed a lot and I have already read a lot of posts here about that, but I still seem to have trouble.
My problem is that I am also a beginner and I don't really understand how ΔΈwork and the try and catch function.
I have been trying to write to a file some string array, but it doesn't appear in there, nor the catch error is displayed in the console. I don't want to use the try method in this case, because when I am, I cannot use the variable declared for let's say BufferedWriter in other places, I am only restricted to the try method. Otherwise, I get a bug.
This is my code:
import java.io.*;
import java.util.*;
import java.lang.*;
public class FileWrit {
public static void main (String[] args){
try(BufferedWriter writer = new BufferedWriter(new FileWriter("testing.txt"))) {
String[] anything = new String[3];
writer.write("anything");
anything[0] = "case1";
anything[1] = "This is 1.5";
anything[2] = "Case 3, i do not know how to count";
for(String mem: anything) {
writer.append(mem);
}
writer.close();
} catch(IOException e) {
System.err.println("Idk when should this appear?");
}
}
}

For the "can't use it anywhere" part of your problem, you could declare the variable outside of the try catch block and only assign it inside. You can do a null check wherever else you want to use it to make sure there's no problems, or assign it another value in the catch block. Like so:
public static void main(String[] args) {
BufferedWriter writer;
String[] anything;
try {
writer = new BufferedWriter(new FileWriter("testing.txt"))) {
anything = new String[3];
writer.write("anything");
anything[0] = "case1";
anything[1] = "This is 1.5";
anything[2] = "Case 3, i do not know how to count";
for (String mem: anything) {
writer.append(mem);
}
writer.close();
} catch (IOException e) {
writer = null;
e.printstacktrace();
}
}
}
if(writer != null){
System.out.println(writer);
}

try and catch it's use for managed the exception. try this code:
import java.io.*;
import java.util.*;
import java.lang.*;
public class FileWrit {
public static void main (String[] args){
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("testing.txt"))
String[] anything = new String[3];
writer.write("anything");
anything[0] = "case1";
anything[1] = "This is 1.5";
anything[2] = "Case 3, i do not know how to count";
for(String mem: anything) {
writer.append(mem);
}
writer.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
The System.err.println("Idk when should this appear?"); appear when you have an Exception in your try "an Error".

Related

It says Process Finished but there is no output

I'm new to java and I'm having a little problem with my code. There's no error and such, it just keeps saying process finished but no output was displayed. The filename is correct as I've checked.
import java.nio.file.;
import java.io.;
public class GuessingGame {
public GuessingGame() {
String filename = "C:\\Users\\angela\\Documents\\words.txt";
Path path = Paths.get(filename.toString());
try {
InputStream input = Files.newInputStream(path);
BufferedReader read = new BufferedReader(new InputStreamReader(input));
String word = null;
while((word = read.readLine()) !=null) {
System.out.println(word);
}
}
catch(IOException ex) {
}
}
public static void main (String[] args) {
new GuessingGame();
}
}
You are ignoring the exception and you don't close the file. Save some typing by using the built-in input.transferTo() for copying the file to System.out, and pass on the exception for the caller to handle by adding throws IOException to constructor and main.
Replace your try-catch block with this try-with-resources, which handles closing the file after use:
try (InputStream input = Files.newInputStream(path)) {
input.transferTo(System.out) ;
}
You managed to call the intended class, but you also needed to specify the specific function which you have declared in the function. Like so:
public static void main (String[] args) { GuessingGame gg = new GuessingGame; gg.GuessingGame(); }

Add data to specific record in CSV file

I have a record in a CSV file and i am trying to add some extra info (a name) to the same specific record with the following code but it does not work. There is no error shown but the info i am trying to add just does not appear. What am i missing ?
public class AddName {
public static void main(String[] args) {
String filepath="Zoo.csv";
String editTerm="Fish";
String addedName="Ron";
addToRecord(filepath,editTerm,addedName);
}
public static void addToRecord(String filepath,String editTerm,String addedName){
String animal= "";
try{
FileWriter fw=new FileWriter(filepath,true);
BufferedWriter bw=new BufferedWriter(fw);
PrintWriter pw=new PrintWriter(bw);
if (animal.equals(editTerm)){
pw.println(editTerm+","+addedName);
pw.flush();
pw.close();
}
System.out.println("Your Record was saved");
}
catch(Exception e){
System.out.println("Your Record was not saved");
e.printStackTrace();
}
}
You could consider using a CSV library to help you out with parsing CSVs because it is more complicated than it looks, especially when it comes down to quoting.
Here's a quick example using OpenCSV that clones the original CSV file and adds "Ron" as necessary:
public class Csv1 {
public static void main(String[] args) throws IOException, CsvValidationException {
addToRecord("animal.csv", "animal-new.csv", "fish", "Ron");
}
public static void addToRecord(String filepathIn, String filepathOut, String editTerm, String addedName)
throws IOException, CsvValidationException {
try (CSVReader reader = new CSVReader(new FileReader(filepathIn))) {
try (CSVWriter writer = new CSVWriter(new FileWriter(filepathOut))) {
String[] values;
while ((values = reader.readNext()) != null) {
if (values.length > 2 && values[0].equals(editTerm)) {
values[1] = addedName;
}
writer.writeNext(values);
}
}
}
}
}
Given the file:
type,name,age
fish,,10
cat,,12
lion,tony,10
will produce:
"type","name","age"
"fish","Ron","10"
"cat","","12"
"lion","tony","10"
(You can look for answers about outputting quotes in the resulting CSV)
Here the requirement is to add an extra column if the animal name matches. It's equivalent to changing a particular line in a file. Here's a simple approach to achieve the same, (Without using any extra libraries),
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class EditLineInFile {
public static void main(String[] args) {
String animal = "Fish";
Path path = Paths.get("C:\\Zoo.csv");
try {
List<String> allLines = Files.readAllLines(path);
int counter = 0;
for (String line : allLines) {
if (line.equals(animal)) {
line += ",Ron";
allLines.set(counter, line);
}
counter++;
}
Files.write(path, allLines);
} catch (IOException e) {
e.printStackTrace();
}
}
}
You may use this code to replace the file content "Fish" to "Fish, Ron"
public static void addToRecord(String filepath, String editTerm, String addedName) {
try (Stream<String> input = Files.lines(Paths.get(filepath));
PrintWriter output = new PrintWriter("Output.csv", "UTF-8"))
{
input.map(s -> s.replaceAll(editTerm, editTerm + "," + addedName))
.forEachOrdered(output::println);
} catch (IOException e) {
e.printStackTrace();
}
}

Program does not run continuously

I'm writing a ChatBot program where, if the ChatBot doesn't have information to answer a question by the user, it asks the user how to answer the question, and then stores it in a txt file. Later, when another question is asked, the information is retrieved from the txt file and the whole thing starts over (or at least is supposed to).
The program works, however, after one query from the user, and I press enter again for a second try, nothing happens anymore.
Here is my code:
import java.io.*;
import java.util.*;
import java.nio.file.*;
import java.util.stream.Stream;
public class Main {
public static void main(String args[]) {
System.out.println("Bot: Hello!! My name's HiBot! What's up?");
System.out.print("You: ");
Scanner input = new Scanner(System.in).useDelimiter("\\n");
String response = input.next();
if (response.toLowerCase().contains("bye") || response.toLowerCase().contains("see ya")
|| response.toLowerCase().contains("gtg")) {
System.out.println("Bot: Ok, see ya. Nice talking to you!");
}
processor(response);
}
public static void processor(String reply) {
try {
BufferedReader reader = new BufferedReader(new FileReader("convos.txt"));
int count = 0;
try {
String line = reader.readLine();
while (line != null) {
count++;
if (line.toLowerCase().contains(reply.toLowerCase())) {
try (Stream<String> lines = Files.lines(Paths.get("convos.txt"))) {
line = lines.skip(count).findFirst().get();
System.out.println("Bot: " + line);
recur();
} catch (IOException e) {
System.out.println("Bot: Something happened πŸ˜•\n" + e);
}
reader.close();
return;
}
reader.close();
}
System.out.println("Bot: Sorry, I'm dumb. How should I reply?");
System.out.print("You: ");
Scanner input = new Scanner(System.in).useDelimiter("\\n");
String response = input.next();
teach(reply, response);
recur();
} catch (IOException e) {
System.out.println("Bot: Something happened πŸ˜•\n" + e);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void teach(String context, String reply) {
try {
try {
FileWriter learn = new FileWriter("convos.txt", true);
PrintWriter out = new PrintWriter(learn);
out.println(context + "\n" + reply);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (IOException e) {
System.out.println("Bot: Something happened πŸ˜•\n" + e);
}
System.out.println("Bot: Thank you for teaching me!! I'm smarter now!");
}
public static void recur() {
int trickLoop = 1;
while (trickLoop > 0) {
System.out.print("You: ");
Scanner input = new Scanner(System.in).useDelimiter("\\n");
String response = input.next();
if (response.toLowerCase().contains("bye") || response.toLowerCase().contains("see ya")
|| response.toLowerCase().contains("gtg")) {
System.out.println("Bot: Ok, see ya. Nice talking to you!");
System.exit(0);
}
processor(response);
}
}
}
I also think that there's definitely a better way to write the code. Does anyone have any suggestions?
EDIT: I have convos.txt but I didn't show it here.
Issue1 :
Initially file doesn't exist and you are not creating it. so it gave following error
Bot: Hello!! My name's HiBot! What's up?
You: hi
java.io.FileNotFoundException: convos.txt (The system cannot find the file specified)
Issue 2 :
You are doing recursion using recur method which can be risky here in the case of continuous inputs as your resources will not be closed right away and can result into further resource starvation issues.
You can simply use infinite while loop.
Improvement1 :
Don't you think that once user inputs bye/see ya/gtg program should close ?
Improvement2 :
Repeated calls to string.toLowerCase() in main method.
Improvement3 :
This line line = lines.skip(count).findFirst().get(); can result into NoSuchElementException
I have added improvement 2 and 3 in the below code.
Here i updated the code below which works as per your details in the question
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
import java.util.stream.Stream;
public class Main {
public static void main(String args[]) {
System.out.println("Bot: Hello!! My name's HiBot! What's up?");
while (true) {
System.out.print("You: ");
Scanner input = new Scanner(System.in).useDelimiter("\\n");
String response = input.next();
String lowercaseResponse = response.toLowerCase();
if (lowercaseResponse.contains("bye") || lowercaseResponse.contains("see ya")
|| lowercaseResponse.contains("gtg")) {
System.out.println("Bot: Ok, see ya. Nice talking to you!");
}
processor(response);
}
}
public static void processor(String reply) {
BufferedReader reader = null;
try {
File file = new File("convos.txt");
if (file.createNewFile())
System.out.println("Conversations file created");
reader = new BufferedReader(new FileReader(file.getName()));
int count = 0;
String line = reader.readLine();
while (line != null) {
count++;
if (line.toLowerCase().contains(reply.toLowerCase())) {
try (Stream<String> lines = Files.lines(Paths.get("convos.txt"))) {
line = lines.skip(count).findFirst().map(Object::toString).orElse("I don't know how to respond");
System.out.println("Bot: " + line);
} catch (IOException e) {
System.out.println("Bot: Something happened while reading conversation file πŸ˜•\n" + e);
}
reader.close();
return;
}
line = reader.readLine();
}
reader.close();
System.out.println("Bot: Sorry, I'm dumb. How should I reply?");
System.out.print("You: ");
Scanner input = new Scanner(System.in).useDelimiter("\\n");
String response = input.next();
teach(reply, response);
} catch (FileNotFoundException e) {
System.out.println("Bot: File not found πŸ˜•\n" + e);
} catch (IOException e) {
System.out.println("Bot: Something happened πŸ˜•\n" + e);
} finally {
try {
reader.close();
} catch (IOException e) {
System.out.println("Bot: Something happened while closing the file reader πŸ˜•\n" + e);
}
}
}
public static void teach(String context, String reply) {
try {
try {
FileWriter learn = new FileWriter("convos.txt", true);
PrintWriter out = new PrintWriter(learn);
out.println(context + "\n" + reply);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (IOException e) {
System.out.println("Bot: Something happened πŸ˜•\n" + e);
}
System.out.println("Bot: Thank you for teaching me!! I'm smarter now!");
}
}
Output : For the first time
Bot: Hello!! My name's HiBot! What's up?
You: hi
Conversations file created
Bot: Sorry, I'm dumb. How should I reply?
You: hello
Bot: Thank you for teaching me!! I'm smarter now!
You:
hi
Bot: hello
You:
Output : When Convos.txt is created already
Bot: Hello!! My name's HiBot! What's up?
You: hi
Bot: hello
You: hi
Bot: hello
You: hi
Bot: hello
You:
Let me know if i missed anything.
I saw this question because someone edited the question.
Here's one test run. The "convos.txt" file exists and has a couple of response / reply text lines.
Bot: Hello! My name's HiBot! What's up?
You: hi
Bot: Hi
You: how are you
Bot: Fine. How are you?
You: Good
Bot: Sorry, I'm ignorant. How should I reply?
You: That's good to hear.
Bot: Thank you for teaching me a new reply! I'm smarter now!
You: bye
Bot: Ok, see ya. Nice talking to you!
I eliminated the multiple System.in Scanner instances. In the reorganized code, I only needed one Scanner instance. There should only be one System.in Scanner instance in your code.
I created a separate ResponseMap class to hold a HashMap for the response / reply text.
I created a separate FileHandler class to handle the reading and writing of the text file. I read the file into the Map once in the beginning. I write the Map into the file once at the end. Even when you have 10,000 response / reply lines, the entire file should easily fit into memory.
Because I made the Map value a List of String instances, you can manually create multiple replies for the same response. This adds a bit of variety to the chatbot.
Here's the complete runnable code.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
public class ChatbotExample {
public static void main(String[] args) {
new ChatbotExample().runChatbot();
}
public void runChatbot() {
Scanner scanner = new Scanner(System.in);
String[] exitResponses = { "bye", "see ya", "gtg" };
List<String> exitList = Arrays.asList(exitResponses);
boolean running = true;
System.out.println("Bot: Hello! My name's HiBot! What's up?");
ResponseMap responseMap = new ResponseMap();
FileHandler fileHandler = new FileHandler(responseMap);
fileHandler.readFile();
while (running) {
System.out.print("You: ");
String response = scanner.nextLine();
String lowercaseResponse = response.toLowerCase();
if (exitList.contains(lowercaseResponse)) {
System.out.println("Bot: Ok, see ya. Nice talking to you!");
running = false;
} else {
generateReply(scanner, responseMap, lowercaseResponse);
}
}
fileHandler.writeFile();
scanner.close();
}
private void generateReply(Scanner scanner, ResponseMap responseMap,
String lowercaseResponse) {
String text = responseMap.getResponse(lowercaseResponse);
if (text == null) {
System.out.println("Bot: Sorry, I'm ignorant. How should I reply?");
System.out.print("You: ");
String reply = scanner.nextLine();
responseMap.addResponse(lowercaseResponse, reply);
System.out.println("Bot: Thank you for teaching me a new reply! "
+ "I'm smarter now!");
} else {
System.out.println("Bot: " + text);
}
}
public class FileHandler {
private final File file;
private final ResponseMap responseMap;
private final String separator;
public FileHandler(ResponseMap responseMap) {
this.responseMap = responseMap;
this.separator = " ;;; ";
this.file = new File("convos.txt");
createFile(this.file);
}
private void createFile(File file) {
try {
if (file.createNewFile()) {
System.out.println("Conversations file created");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void readFile() {
try {
BufferedReader reader = new BufferedReader(
new FileReader(file));
String line = reader.readLine();
while (line != null) {
String[] parts = line.split(separator);
responseMap.addResponse(parts[0], parts[1]);
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeFile() {
try {
FileWriter writer = new FileWriter(file, false);
PrintWriter output = new PrintWriter(writer);
Map<String, List<String>> responses = responseMap.getResponses();
Set<String> responseSet = responses.keySet();
Iterator<String> iterator = responseSet.iterator();
while (iterator.hasNext()) {
String key = iterator.next();
List<String> text = responses.get(key);
for (String reply : text) {
String s = key + separator + reply;
output.println(s);
}
}
output.flush();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class ResponseMap {
private final Map<String, List<String>> responses;
private final Random random;
public ResponseMap() {
this.responses = new HashMap<>();
this.random = new Random();
}
public Map<String, List<String>> getResponses() {
return responses;
}
public String getResponse(String key) {
List<String> possibleResponses = responses.get(key);
if (possibleResponses == null) {
return null;
} else {
int index = random.nextInt(possibleResponses.size());
return possibleResponses.get(index);
}
}
public void addResponse(String key, String text) {
List<String> possibleResponses = responses.get(key);
if (possibleResponses == null) {
possibleResponses = new ArrayList<>();
responses.put(key, possibleResponses);
}
possibleResponses.add(text);
}
}
}

How to figure out why file is missing when trying to Run Configurations (set an Argument in Java)?

Hello everyone, Java beginner here. I am trying to run some java code in eclipse IDE, and set my args x = 25 from
Run > Run Configurations > Arguments > Apply > Run. However, before I can get to Arguments, I get this error message (see photo below). Does anyone know what this means or why I am getting this? What does this specific '.metadata/.plugins/org.eclipse.debug.core' do?
MY CODE BELOW:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
public class IOTest {
public IOTest () {
}
public void readFile () {
try {
FileReader file = new FileReader("movies.txt");
BufferedReader br = new BufferedReader(file);
String line = br.readLine();
while (line != null) {
System.out.println(line);
line = br.readLine();
}
br.close();
} catch (Exception e) {
System.out.println("Unable to load file.");
}
}
public void writeFile () {
try {
FileWriter file = new FileWriter("tvshows.txt");
BufferedWriter bw = new BufferedWriter(file);
bw.write("Seinfeld\n");
bw.write("Breaking Bad\n");
bw.write("The Simpsons\n");
bw.write("Family Guy\n");
bw.close();
} catch (Exception e) {
System.out.println("Unable to load/create file.");
}
}
public static void main(String[] args) {
IOTest test = new IOTest();
test.readFile();
test.writeFile();
if (args.length == 1) {
// Do something.
int x = Integer.parseInt(args[0]);
System.out.println("x = " + x);
} else {
// Do something else.
}
}
}

Runtime.exec() in java hangs because it is waiting for input from System.in

I have the following short python program "test.py"
n = int(raw_input())
print n
I'm executing the above program from following java program "ProcessRunner.java"
import java.util.*;
import java.io.*;
public class ProcessRunner {
public static void main(String[] args) {
try {
Scanner s = new Scanner(Runtime.getRuntime().exec("python test.py").getInputStream()).useDelimiter("\\A");
System.out.println(s.next());
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}
}
Upon running the command,
java ProcessRunner
I'm not able to pass a value 'n' in proper format to Python program and also the java run hangs. What is the proper way to handle the situation and pass a value to 'n' dynamically to python program from inside java program?
raw_input(), or input() in Python 3, will block waiting for new line terminated input on standard input, however, the Java program is not sending it anything.
Try writing to the Python subprocess using the stream returned by getOutputStream(). Here's an example:
import java.util.*;
import java.io.*;
public class ProcessRunner {
public static void main(String[] args) {
try {
Process p = Runtime.getRuntime().exec("python test.py");
Scanner s = new Scanner(p.getInputStream());
PrintWriter toChild = new PrintWriter(p.getOutputStream());
toChild.println("1234"); // write to child's stdin
toChild.close(); // or you can use toChild.flush()
System.out.println(s.next());
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}
}
An alternative is to pass n as a command line argument. This requires modification of the Python script to expect and process the command line arguments, and to the Java code to send the argument:
import java.util.*;
import java.io.*;
public class ProcessRunner {
public static void main(String[] args) {
try {
int n = 1234;
Process p = Runtime.getRuntime().exec("python test.py " + n);
Scanner s = new Scanner(p.getInputStream());
System.out.println(s.next());
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}
}
And the Python script, test.py:
import sys
if len(sys.argv) > 1:
print int(sys.argv[1])
If I understand you correctly you want your java program to pass any output from your python script to System.out and any input into your java program to your python Script, right?
Have a look at the following program to get an idea how you could do this.
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class ProcessRunner {
public static void main(String[] args) {
try {
final Process process = Runtime.getRuntime().exec("/bin/sh");
try (
final InputStream inputStream = process.getInputStream();
final InputStream errorStream = process.getErrorStream();
final OutputStream outputStream = process.getOutputStream()
) {
while (process.isAlive()) {
forwardOneByte(inputStream, System.out);
forwardOneByte(errorStream, System.err);
forwardOneByte(System.in, outputStream);
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static void forwardOneByte(final InputStream inputStream,
final OutputStream outputStream)
throws IOException {
if(inputStream.available() <= 0) {
return;
}
final int b = inputStream.read();
if(b != -1) {
outputStream.write(b);
outputStream.flush();
}
}
}
Note This code is just a concept demo. It will eat up your cpu and will not be able to cope with bigger amounts of throughput.

Categories