The problem is it finds the key word "dodge" creates the file but doesn't write to it. I had this problem earlier and I flushing then closing the file fixed it, but that did not work this time.
Also WriteToFile(CurrentLine[ReturnWordsIndex("using")-1]); towards the bottom errors out and says ArrayIndexOutOfBoundsException: -2 I'm not sure why because "using" should never be found at position -1.
import java.io.*;
import javax.swing.JOptionPane;
public class InputLog {
private BufferedReader CombatLog;
private PrintWriter CharacterFile;
private String[] CurrentLine;
InputLog(){
try{
CombatLog = new BufferedReader(new FileReader("127401175162_chatlog.txt"));
do{
try{
CurrentLine = CombatLog.readLine().split(" ");
}
catch(IOException e){
JOptionPane.showMessageDialog(null, "Sorry cannot open UserSettings File");
}
DetermineType();
}while(CombatLog.ready());
CharacterFile.close();
}
catch(IOException e){
JOptionPane.showMessageDialog(null, "Could not open next line of combatlog " + e);
}
}
public void WriteToFile(String S){
try{
CharacterFile = new PrintWriter(new File(CurrentLine[3]));
}
catch(IOException e){
JOptionPane.showMessageDialog(null, "Sorry can't write " + CurrentLine[3] +" To file");
}
CharacterFile.flush();
CharacterFile.print(S+ " ");
}
public void WriteToFileLn(String S){
try{
CharacterFile = new PrintWriter(new File(CurrentLine[3]));
}
catch(IOException e){
JOptionPane.showMessageDialog(null, "Sorry can't write " + CurrentLine[3] +" To file");
}
CharacterFile.flush();
CharacterFile.println(S+ " ");
}
public int ReturnWordsIndex(String S){
for(int i=0;i<CurrentLine.length;i++){
if(CurrentLine[i].equals(S))
return i;
}
return -1;
}
private void DetermineType(){
for(String A: CurrentLine)
if(A.equals("attacks")){
JOptionPane.showMessageDialog(null, "found dodge");
WriteToFile(CurrentLine[2]);
WriteToFile(CurrentLine[ReturnWordsIndex("using")-1]);
WriteToFile("(dodge).");
WriteToFileLn(CurrentLine[ReturnWordsIndex("attacks")-1]);
}
}
public static void main(String args[]){
new InputLog();
}
}
Thanks, Macaire
Edit: I found out that i am simply writing one string, creating a new file, then writing another character. How can i not delete the file, and just rewrite to it?
How can i not delete the file, and just rewrite to it?
I assume that you mean append to it. (What you are currently doing is rewriting it.)
If so, just use FileWriter(file, true) to create a Writer that will start writing at the current end of the file; e.g.
CharacterFile = new PrintWriter(new FileWriter(new File(CurrentLine[3])));
Note: it is bad style for a Java variable or method name to start with an upper-case letter.
WriteToFile(CurrentLine[ReturnWordsIndex("using")-1]); causes an ArrayIndexOutOfBoundsException: -2 because the word "using" is not found (so ReturnWordsIndex("using") returns -1).
You need an if/then statement so that you don't try to index CurrentLine if the word wasn't found.
In response to your edit, open the file outside of the WriteToFile and WriteToFileLn functions.
Related
im writing a program that subs out any spaces with hypens. The program compiles but it inserts a hyphen at the beginning of the program instead of every instance of a space the source code is as follows:
package Exercises;
import java.io.*;
import java.util.Scanner;
public class filehyphen {
public static void main(String[] args)
throws IOException{
DataOutputStream wr;
DataInputStream re;
Scanner type = new Scanner(System.in);
FileOutputStream text;
FileInputStream open;
String OgTxt;
try {
wr = new DataOutputStream(new FileOutputStream("random.txt"));
System.out.println(" Type whatever youd like");
OgTxt = type.nextLine();
wr.writeUTF(OgTxt);
System.out.println(" heres what you typed : " + OgTxt);
wr.close();
type.close();
}
catch(IOException exc) {
System.out.println("cannot write to this file");
}
System.out.println("heres what the text would be with spaces as hyphens");
try {
re = new DataInputStream(new FileInputStream("random.txt"));
OgTxt = re.readUTF();
if(OgTxt.contains(" ")) {
System.out.print("'");
System.out.println(OgTxt);
re.close();
}
}
catch(IOException exc) {
System.out.println("Read error");
}
I think it has something to with the contains method but im not sure. Answers appreciated. Thanks you!!
I have provided the Main method below for your solution.
public static void main(String[] args) throws IOException{
DataOutputStream wr;
DataInputStream re;
Scanner type = new Scanner(System.in);
FileOutputStream text;
FileInputStream open;
String OgTxt;
try {
wr = new DataOutputStream(new FileOutputStream("random.txt"));
System.out.println("Type whatever youd like");
OgTxt = type.nextLine();
wr.writeUTF(OgTxt);
System.out.println("heres what you typed : " + OgTxt);
wr.close();
type.close();
}
catch(IOException exc) {
System.out.println("cannot write to this file");
}
System.out.println("heres what the text would be with spaces as hyphens");
try {
re = new DataInputStream(new FileInputStream("random.txt"));
OgTxt = re.readUTF();
String replacedString = OgTxt.replace(" ", "-");
System.out.println(replacedString);
re.close();
}
catch(IOException exc) {
System.out.println("Read error");
}
}
I removed the if statement in your second try...catch block and made use of the replace method provided natively by the String class.
In your post you say that spaces should be replaced by hyphens, however you are trying to replace spaces with single quotation marks. Assuming you meant hyphens I corrected that.
I have these three methods and I am trying to write the contents of three lists to a file using the buffered writer.
First Method: To Save File:
public static String showSaveDialog()
{
String fileName = "";
JFileChooser chooser = new JFileChooser();
// Suggesting a name
chooser.setSelectedFile(new File("fileToSave.txt"));
int resultValue = chooser.showSaveDialog(null);
if (resultValue == JFileChooser.APPROVE_OPTION) {
fileName = chooser.getSelectedFile().getAbsolutePath();
Path = chooser.getSelectedFile().getAbsolutePath();
}
writeToTextFile(fileName, "");
return fileName;
}
Second Method: To write To File:
public static void writeToTextFile(String filePath, String toWrite)
{
BufferedWriter writer = null;
try {
writer = Files.newBufferedWriter(Paths.get(filePath),
StandardOpenOption.CREATE);
writer.write(toWrite);
writer.newLine();
writer.close();
}
catch (IOException ex) {
JOptionPane.showMessageDialog(null,
"Saving File Error: " + ex.getMessage(),
"Saving File Error", JOptionPane.ERROR_MESSAGE);
}
}
Third Method: Write Contents of three lists to text file:
public void saveAllQuestions() {
for (String q : questionList){
FileIO.writeToTextFile(FileIO.Path, "$" + q);
for (int i = 0; i < answerList.size(); i++) {
FileIO.writeToTextFile(FileIO.Path,
answerList.get(i) + ", " + correctAnswers.get(i));
}
}
}
When writing to the file the last line is the only one that shows. I am assuming this problem is due to the fact that it is writing to one line only instead of under each other. Can anybody give me some insight please? Thank you
You are opening and closing the file for every line you write. Each time you write a line you are deleting the previous version of the file and replacing it with that one line. You need to open the file, write all the lines, and then close the file.
So, I've been trying to learn java from various sources, I've been learning for about 2 years now. So far everything has been going smoothly, i haven't had to post on stackoverflow for a while. Recently I've been trying to figure out how to create and read files with java. I can do both of those things in separate apps, but when i try to do both it doesn't always work.
What i want to happen:
I want my program to create data.txt, then I want it to read the data and produce an error log on error.txt.
What happens:
The data.txt file gets created as expected, but nothing is written to the error.txt file. I'm having trouble grasping the try/catch block and how exactly it works. Anyone got any ideas? even just some advice would be appreciated. Thanks!
import java.io.*;
import java.util.Scanner;
public class dataReader {
public static void main(String args[]) throws Exception {
File fileName;
fileName = new File("data.txt");
PrintWriter outputFile;
outputFile = new PrintWriter(fileName);
File errorFile;
errorFile = new File("errors.txt");
PrintWriter outputErrorFile;
outputErrorFile = new PrintWriter(errorFile);
Scanner inputFile;
int recordNumber = 0;
String inputData;
outputFile.println(77);
outputFile.println("Fred");
outputFile.println(92);
outputFile.println("Wilma");
outputFile.println(89.9);
outputFile.println("Barney");
outputFile.println(42);
outputFile.println("BettyS");
inputFile = new Scanner(fileName);
while (inputFile.hasNext()) {
recordNumber++;
try {
inputData = inputFile.nextLine();
if (Integer.parseInt(inputData) < 50) {
outputErrorFile.println(recordNumber + ", " + inputData + ", is less than 50.");
} else if (Integer.parseInt(inputData) > 90) {
outputErrorFile.println(recordNumber + ", " + inputData + ", is less than 50.");
}
} catch (Exception e) {
outputErrorFile.println(recordNumber + ", That's not an integer.");
}
}
outputFile.close();
outputErrorFile.close();
System.out.println("Program terminated.");
}
}
Move the outputFile.close(); line before inputFile = new Scanner(fileName);. Currently it's just cached in the memory and not written actually to the disk.
The documentation of PrintWriter says it all. The PrintWriter(Writer) constructor creates a writer which is not automatically flushed.
You have to call close or flush method to write your data to the file.
So you have to use outputFile.close(); method before starting reading.
and as a good practice you have to close all your PrintWriter instances to avoid memory leak.
just in this case please add inputFile.close(); at the end of your program.
I just did a simple code which takes user name and phone number and save those into an arraylist by creating object. I want to save those information (name and phonenumber) into a text file so that all old information I can get again. How do I do it? Here is my code ...
import java.util.ArrayList;
import java.util.Scanner;
public class manager {
Scanner input = new Scanner(System.in);
ArrayList <objectclass> Test = new ArrayList <objectclass> ();
public void mainloop() {
for (int i = 0; i < 100; i++) {
String x;
System.out.println("Please Select your option");
System.out.println("............................");
System.out.println("1 ADD NAME AND NUMBER\n2 SEARCH NAME AND NUMBER \n0 EXIT");
System.out.println("............................");
x = input.nextLine();
if (x.equalsIgnoreCase("0")) {
System.out.println("Thank you!");
break;
}
if (x.equalsIgnoreCase("1")) {
String Name;
String Number;
System.out.println("Please Enter your Name below");
Name = input.nextLine();
System.out.println("Please Enter your Number below");
Number = input.nextLine();
objectclass objectclassObject = new objectclass(Name, Number);
Test.add(objectclassObject);
}
if (x.equalsIgnoreCase("2")) {
String y;
System.out.println("*** Enter your Name below for search ***");
y = input.nextLine();
for (objectclass p : Test) {
String z = p.getName();
if (z.equalsIgnoreCase(y)) {
System.out.println("Your Name is: " + p.getName() + "\nYour Number is: " + p.getNumber());
System.out.println("");
} else {
System.out.println("Contact not Found!\n");
}
}
}
}
}
}
I want to save all name and number that I store in arraylist into a text file ... how can I do it?
I tried this so far but don't know what to do next ...
import java.io.;
import java.lang.;
import java.util.*;
public class creatfile {
private Formatter x;
public void openFile(){
try{
x = new Formatter("testkyo");
}catch (Exception e){
System.out.println("you have an error");
}
}
public void addRecord(){
x.format();
}
public void closeFile(){
x.close();
}
You need to serialize an object in order to save it onto the file .
here's a tutorial on how to do it, its really simple.
When you serialize an object you can write it onto a file and then load it as it is from there .
EDIT :
example on how you could use this here , i guess the ObjectClass is the thing u want to save so :
class ObjectClass implements Serializable {
String name;
String number;
//constructor , setters , getters and w.e functions .
public static void main (String args[]){
try{
ObjectClass test = new ObjectClass("test",2);
File f = new File("path to file");
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f));
out.writeObject(test); // this will write the object as it is onto the file
out.close();
}catch(Exception ex){}
}
}
you wont be able to read the data cuz its serialised , but u can load them as objects like so :
ObjectInputStream in = new ObjectInputStream(new File("path to file"));
ObjectClass test =(ObjectClass) in.readObject(); // u have to cast from Object to Objectclass
what you propably want is an ObjectOutputstream writing your ArrayList to a file via an FileOutputStream when the porgram is exiting and reading the Arraylist with the coresponding InputStreams. See the links below:
http://docs.oracle.com/javase/7/docs/api/java/io/ObjectOutputStream.html
http://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html
A simple example:
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter("./output.txt"));
writer.write("Hello World");
} catch (IOException e) {
System.err.println(e);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
System.err.println(e);
}
}
}
This will write "Hello World" in the text file named: "output.txt".
Check the java I/O api.
You can find a lot of tutorials on the web about this, like:
Reading, Writing, and Creating Files
Creating, Writing, Reading files using Java Files API of Java 7
I was asked to write an assignment wherein the user would be prompted to input a key and/or a value.
So far, here is my code:
import java.util.Scanner;
import java.io.*;
class bTree
{
//Fields
static Scanner input = new Scanner(System.in);
static boolean done = false;
public static void main(String args[])throws Exception
{
FileWriter fWriter = new FileWriter("data.txt");
do
{
System.out.print("Enter command: ");
String enter[] = input.nextLine().split(" ", 3);
if(enter[0].toLowerCase().equals("insert"))
{
fWriter.write(enter[1] + "\n" + enter[2] + "\n");
fWriter.flush();
}
else if(enter[0].toLowerCase().equals("select"))
{
FileReader fReader = new FileReader("data.txt");
Scanner fileInput = new Scanner(fReader);
while(fileInput.hasNext() && done == false)
{
if(fileInput.nextLine().equals(enter[1]))
{
System.out.println(fileInput.nextLine());
done = true;
}
else
{
fileInput.nextLine();
}
}
done = false;
}
else if(enter[0].toLowerCase().equals("update"))
{
fWriter.write(enter[2]);
fWriter.flush();
}
else if(enter[0].toLowerCase().equals("exit"))
{
System.exit(0);
}
}
while(true);
}
}
Problem: When i open the data.txt, there are no spaces. So if i enter "insert 1001 gen" and "10001 genny", in notepad, it would come out as "1001gen10001genny". Any suggestions?
The problem is that notepad.exe is picky about line endings, and there are many possibilities. When you write "\n" to a FileWriter, it writes a single character, namely '\n'. But notepad expects the sequence "\r\n" instead. It shows a single "\n" as nothing.
Here is your code, slightly modified to work around some pitfalls.
package so7696816;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.Locale;
import java.util.Scanner;
public class Excercise {
public static void main(String args[]) throws Exception {
final Scanner input = new Scanner(System.in);
PrintWriter fWriter = new PrintWriter("data.txt");
while (true) {
System.out.print("Enter command: ");
String enter[] = input.nextLine().split(" ", 3);
final String command = enter[0].toLowerCase(Locale.ROOT);
if (command.equals("insert")) {
fWriter.println(enter[1]);
fWriter.println(enter[2]);
fWriter.flush();
} else if (command.equals("select")) {
FileReader fReader = new FileReader("data.txt");
Scanner fileInput = new Scanner(fReader);
while (fileInput.hasNextLine()) {
String key = fileInput.nextLine();
String value = fileInput.nextLine();
if (key.equals(enter[1])) {
System.out.println(value);
break;
}
}
fReader.close(); // don't leave files open
} else if (command.equals("update")) {
fWriter.write(enter[2]);
fWriter.flush();
} else if (command.equals("exit")) {
return;
} else {
System.err.println("Unknown command: " + command);
}
}
}
}
Remarks:
I used a PrintWriter instead of a FileWriter to get the line endings correct.
For the select command I closed the fReader after using it.
I avoided to type enter[0].toLowerCase() multiple times.
I used the proper variant of toLowerCase.
I added error handling for unknown commands.
I rewrote the select command to be a little more concise.
The problem is String enter[] = input.nextLine().split(" ", 3);, it kills the Spaces. So append a space after each array entry or write an additional " " everytime you use fWriter.write.
look here
As already stated the line feed character is incorrect for notepad. Alternatively you could wrap that FileWriter in a BufferedWriter and use the newLine method to always insert the correct line feed.
I think you are running your program in UNIX. In unix system "\r\n" is the line feed.
If you are running your program in Windows, I think the file should contain something like this.
1001
gen
10001
genny