Saving an ArrayList to .txt file - java

So, I was wondering if it's possible to save values from an ArrayList to a file, such as "inputs.txt". I've seen a question similar to this: save changes (permanently) in an arraylist?, however that didn't work for me, so I'm wondering if I'm doing something wrong. Here are my files:
Main.class
package noodlegaming.geniusbot.main;
import java.io.*;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
import java.util.logging.Logger;
public class Main {
public static Random rand = new Random();
public static void readFileByLine(String fileName) {
try {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
SentencesToUse.appendToInputtedSentences(scanner.next().toString());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
static File inputsFile = new File("inputs.txt");
static PrintWriter printWriter = new PrintWriter(inputsFile);
public static void main(String[] args) throws IOException, InterruptedException {
if(!inputsFile.exists()) {
inputsFile.createNewFile();
}
readFileByLine("inputs.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Hello, welcome to GeniusBot. Shortly, you will be speaking with a computer that learns from what you say.");
System.out.println("Because of this circumstance, we ask that you do not type any curses, swear words, or anything otherwise considered inappropriate,");
System.out.println("as it may come back to the light at a time you don't want it to.");
System.out.println("Please note that your responses won't be saved if you close the program.");
System.out.println("If you type printInputsSoFar, a list of all the stuff you've typed will be printed.");
System.out.println("If you type printInputsLeft, the number of inputs you have left will be printed.");
System.out.println("If you type clearInputs, the program will be closed and the inputs.txt file deleted, " +
"\nand recreated upon startup.");
System.out.println("Starting up GeniusBot.");
Thread.sleep(3000);
System.out.println("Hello! I am GeniusBot!");
br.readLine();
System.out.println("" + SentencesToUse.getBeginningSentence() + "");
for (int i = 0; i < 25; i++) {
String response = br.readLine();
if (response.equals("printInputsSoFar")) {
for (int j = 1; j < SentencesToUse.inputtedSentences.size(); j++) {
System.out.println(SentencesToUse.inputtedSentences.get(j));
}
i--;
} else if (response.equals("printInputsLeft")) {
int inputsLeft = 25 - i;
System.out.println("You have " + inputsLeft + " inputs left.");
i--;
} else if (response.equals("clearInputs")) {
printWriter.close();
inputsFile.delete();
Thread.currentThread().stop();
} else {
SentencesToUse.appendToInputtedSentences(response);
printWriter.println(response);
printWriter.flush();
int inputtedSentence = Main.rand.nextInt(SentencesToUse.inputtedSentences.size());
String inputtedSentenceToUse = SentencesToUse.inputtedSentences.get(inputtedSentence);
System.out.println(inputtedSentenceToUse);
}
if (i == 24) {
System.out.println("Well, it was nice meeting you, but I have to go. \nBye.");
Thread.currentThread().stop();
printWriter.close();
}
}
}
}
SentencesToUse.class:
package noodlegaming.geniusbot.main;
java.util.ArrayList;
import java.util.List;
public class SentencesToUse {
public static String[] beginningSentences = {"What a lovely day!", "How are you?", "What's your name?"};
static int beginningSentence = Main.rand.nextInt(beginningSentences.length);
static String beginningSentenceToUse = beginningSentences[beginningSentence];
public static String getBeginningSentence() {
return beginningSentenceToUse;
}
public static List<String> inputtedSentences = new ArrayList<String>();
public static void appendToInputtedSentences(String string) {
inputtedSentences.add(string);
}
public static void clearInputtedSentences() {
inputtedSentences.clear();
}
}

As stated in the comments, use a PrintWriter to write the values to a file instead:
PrintWriter pw = new PrintWriter(fos);
for (int i = 0; i < SentencesToUse.inputtedSentences.size(); i++) {
pw.write(SentencesToUse.inputtedSentences.get(i)+"\n"); // note the newline here
}
pw.flush(); // make sure everything in the buffer actually gets written.
And then, to read them back again:
try {
Scanner sc = new Scanner(f);
while (sc.hasNext()) {
SentencesToUse.inputtedSentences.ass(sc.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
The pw.flush(); is incredibly important. When I was first learning java, I can't tell you how many hours I spent debugging because I didn't flush my streams. Note also the "\n". This ensures that there will be a newline, and that your sentences don't just run together in one giant blob. If each one already has a newline, then that's not necessary. Unlike print vs println, there is no writeln. You must manually specify the newline character.

Related

Adding a substring to omit a part of the output

Below is my code...
The code below is taking a .txt file of some radiation read outs. My job is to find the max number of counts per minute in the file within 5 counts.
I'e got it working, but I need to omit the part of the line, so I thought I could make this piece of the code:
/* String temp = new String(data)
* temp=list.get(i);
* System.outprintln(temp.substring(0,16) +" ");
*/
and integrate it in. I keep trying several cases, and am not thinking. Any advice?
`import java.util.*;
//Import utility pack, *look at all classes in package.
import java.io.*;
//Good within directory.
public class counterRadiation {
private static String infile = "4_22_18.txt";
//Input
private static String outfile = "4_22_18_stripped.txt";
private static Scanner reader;
//Output
public static void main(String[] args) throws Exception{
//throw exception and then using a try block
try {
//Use scanner to obtain our string and input.
Scanner play = new Scanner(new File(infile));
/* String temp = new String(data)
* temp=list.get(i);
* System.outprintln(temp.substring(0,16) +" ");
*/
Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outfile), "utf-8"));
String lineSeparator = System.getProperty("line.separator");
play.useDelimiter(lineSeparator);
while (play.hasNext()) {
String line = play.next();
if (line.matches(dataList)) {
writer.write(line + "\r\n");
}
}
writer.close();
play.close();
try {
reader = new Scanner(new File(infile));
ArrayList<String> list = new ArrayList<String>();
while (reader.hasNextLine()) {
list.add(reader.nextLine());
}
int[] radiCount = new int[list.size()];
for (int i = 0; i < list.size();i++) {
String[] temp = list.get(i).split(",");
radiCount[i] = (Integer.parseInt(temp[2]));
}
int maxCount = 0;
for (int i = 0; i < radiCount.length; i++) {
if (radiCount[i] > maxCount) {
maxCount = radiCount[i];
}
}
for (int i = 0;i < list.size() ;i++) {
if(radiCount[i] >= maxCount - 4) {
System.out.println(list.get(i)+" "+ radiCount[i]);
}
}
}catch(FileNotFoundException e){
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}`
Although it is not quite clear what you want to get rid of you could use .indexOf(String str) to define the first occurrence of the sub-string you want to exclude. For example in your code:
String data = "useful bit get rid of this";
int index = data.indexOf("get rid of this");
System.out.println(data.substring(0,index) + "are cool");
//Expected result:
//"useful bits are cool"
from Java doc

Find line number and content of a line and then find open same line number in another file JAVA

I got this code to open up a file and getting the line number, but if I want to open up another file where the content is not the same as the first file and find the same line number, how can I do that the best way? Where do I go from here?
I'm new to this site and to Java so please go easy on me...
public class c {
public static void main(String args[]) {
File file =new File("one.txt");
Scanner in = null;
try {
int counter = 0;
in = new Scanner(file);
while(in.hasNext()) {
counter++;
String line=in.nextLine();
if(line.contains("umbrella")) {
System.out.println(line + " line: " + counter);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
You can just open the other file, and read the lines and increment a counter (counter2) until your counter2 reaches your counter-Variable (from above code-snippet). You also have to notice if the file hasn't ended.
The Code is has many similar Elements like the one you already used in your question.
The best way would depend on the context at which you are developing. You could just create additional instances of File and Scanner classes to operate on a different file as you already done in your code and mentioned in comment already.
Another method would be to create a class that would process this for you. In this case you could use this class for an unlimited number of files that you need to accomplish the same.
public class FileLineCounter {
public FileLineCounter( String filename)
{
try
{
f = new File(filename);
s = new Scanner(f);
}
catch(FileNotFoundException ex)
{
ex.printStackTrace();
}
}
public int getLineNumber( String item)
{
counter = 0;
while( s.hasNext())
{
counter++;
String line = s.nextLine();
if (line.contains(item))
{
break;
}
}
return counter;
}
private File f;
private Scanner s;
private int counter;
};
package FileUtil;
import FileUtil.FileLineCounter;
public class Main {
public static void main(String[] args)
{
String file1 = "one.txt";
String file2 = "two.txt";
FileLineCounter f1 = new FileLineCounter(file1);
FileLineCounter f2 = new FileLineCounter(file2);
System.out.println( file1 + " line : " + f1.getLineNumber("umbrella"));
System.out.println( file2 + " line : " + f2.getLineNumber("umbrella"));
}
}

Java: Counter Indentation

I am very new to java and trying to create a java app which (when ran inside a terminal) will copy what text is inside and if there is a curly { bracket then add 3 spaces, when there is a curly } bracket then remove 3 spaces. There should be a counter to indent another 3 spaces each time a { appears (see example)
Example:
File1.txt:
Hello{StackOverflow}{Users}
The output should be File2.txt:
Hello
{
StackOverflow
}
{
Users
}
What I currently get outputed to File2.txt is:
Hello
{
StackOverflow
}
{
Users
I am missing my last bracket (how do I fix this?) and don't know how to loop my indentation based on the counter. Please help
My current code:
import java.io;
import java.util.Scanner;
public class myapp {
public static void main(String[] argv) throws IOException {
File InputFile = new File(argv[0]);
Scanner FileScanner = new Scanner(InputFile);
FileWriter Writer = new FileWriter(argv[1]);
BufferedWriter OutputWriter = new BufferedWriter(Writer);
while (FileScanner.hasNextLine() == true) {
String a = FileScanner.nextLine();
try {
int indent = 0;
{
if (a.contains("{")) {
indent++;
}
for (int i = 0; i < indent; i++) {
OutputWriter.write(" ");
}
OutputWriter.write(a);
}
if (a.contains("}")) {
indent--;
}
} catch (Exception e) {
System.out.println("Error:" + e.getMessage());
}
OutputWriter.write("}");
}
}
}
p.s in Terminal (to run/test) I use the following command:
$java myapp File1.txt File2.txt
Thank you :)
Try closing OutputWriter at the end of the method via OutputWriter.close(). It will flush the stream which is likely the cause of the missing }.
As far as your indentation issue, declare and initialize the indent counter outside the loop. Otherwise, it will get reset to 0 with each iteration.
Try this one:
public static void main(String[] args) throws IOException {
File InputFile = new File(argv[0]);
Scanner FileScanner = new Scanner(InputFile);
FileWriter Writer = new FileWriter(argv[1]);
BufferedWriter OutputWriter = new BufferedWriter(Writer);
while (FileScanner.hasNextLine() == true) {
String a = FileScanner.nextLine();
String b = "";
for (int i = 0; i < a.length(); i++) {
if (a.charAt(i) == '{') {
b += "\n{\n ";
} else if (a.charAt(i) == '}') {
b += "\n}\n";
} else {
b += a.charAt(i);
}
}
OutputWriter.write(b);
OutputWriter.close();
}}}
Try this it's ok I add the finally block.`
finally{
OutputWriter.close();
}

Java Scanner Read from File

Let me first establish the following fact: I am new to java, so please be patient.
In my programming class, we were given an exercise to do at home using the Scanner class. The activity shows the following coding to exercise with:
import java.io.*;
import java.util.*;
public class FileReadWrite {
public static void main(String[] args) throws FileNotFoundException {
String[] strArr = new String[100];
int size = 0;
try {
Scanner scFile = new Scanner(new File("Names1.txt"));
while (scFile.hasNext()) {
strArr[size] = scFile.next();
size++;
}
scFile.close();
for (int i = 0; i < size; i++) {
System.out.print(strArr[i] + " ");
}
} catch (FileNotFoundException e) {
System.err.println("FileNotFoundException: " + e.getMessage());
}
}
}
The program seems to not be working correct. I use NetBeans to run the code, and when I run the code, it does not display the data in the text file, Names.txt. Why is that? The program does however Build completely without errors.
I have tried going through the Scanner class javadocs, but it's not helping me.
Please explain to me so that I can learn from the mistake made.
Thanks,
Johan
I tried your code on my mac, and it works. So I thought you might input a wrong path of Names1.txt file.
In Java, when you simply use "what_ever_file_name.txt" as the path of file, Java will only search the file in your source code folder. If nothing found, a "FILE_NOT_FOUND_EXCEPTION" will be thrown.
I agree with user2170674. I also tried your code in a Windows machine, using Eclipse, and everything went well. Maybe you are putting your file in the wrong path. Two options:
you could use the full path, like (if you're using Windows) "C:\Names1.txt";
or, a more generic solution, using JFileChooser:
// create your FileChooser
final JFileChooser chooser = new JFileChooser();
// open the FileChooser
int returnValue = chooser.showOpenDialog(null);
// if you select a file
if (returnValue == JFileChooser.APPROVE_OPTION) {
// get the file and do what you need
File file = chooser.getSelectedFile();
} else {
// throw an exception or just a message in the log...
}
Your code looks good.
Debug with a few messages.
At end, add a System.out.println() or System.out.flush().
Move exception block location to just after file use (minimise try block size) and move close() within finally block.
Make sure you view Netbeans output window (Window -> Output -> Output)
public class FileReadWrite {
public static void main(String[] args) throws FileNotFoundException {
System.out.println("##### Starting main method...");
String[] strArr = new String[100];
int size = 0;
try {
Scanner scFile = new Scanner(new File("Names1.txt"));
while (scFile.hasNext()) {
strArr[size] = scFile.next();
size++;
}
System.out.println("##### Finished scan. Found %d tokens.", size);
} catch (FileNotFoundException e) {
System.err.println("FileNotFoundException: " + e.getMessage());
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
e.printStackTrace();
} finally {
if (scFile != null) {
scFile.close();
System.out.println("##### Closed scanner.");
}
}
System.out.println("##### Printing tokens...");
for (int i = 0; i < size; i++) {
System.out.print(strArr[i] + " ");
}
System.out.println("");
System.out.println("##### Exiting main.");
}
}
Here's a working example. Perhaps try using a BufferedReader.
import java.io.*;
import java.util.Scanner;
public class ScanXan {
public static void main(String[] args) throws IOException {
Scanner s = null;
try {
s = new Scanner(new BufferedReader(new FileReader("xanadu.txt")));
while (s.hasNext()) {
System.out.println(s.next());
}
} finally {
if (s != null) {
s.close();
}
}
}
}
From http://docs.oracle.com/javase/tutorial/essential/io/scanning.html

Importing a .dat File Java

I've searched the internet for roughly an hour and a half now, and I can't for the life of me figure out where I've gone wrong.. Help!!
My problem is that every time I try and run it I don't receive an error until it searches for the file and without fail, it replies "File not found." I'm on a MAC I think I'm typing the directory in properly but something is messed up..
(When opening numEven.dat)
For my input I've tried "numEven.dat" (placing the dat file in the same directory as the java file)
I've also tried "/Users/java/numEven.dat" and "Users/java/numEven.dat"
I know it is in that directory. What am I doing wrong?
Main Class file:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class StatDriver
{
public static void main(String[] args)
{
String fileName = "";
Scanner scan = new Scanner(System.in);
double[] array = new double[20];
System.out.print(" Enter file name: ");
fileName = scan.next();
System.out.println("\n \n \n \n My Grades - View Statistics");
System.out.println(" ------------------------");
// int valueCount = readFile(array,fileName);
array = readFile(array, fileName);
Stat stat = new Stat(array, array.length);
// call each calc on Stat class and display results for each method
stat.calcAvg();
stat.calcMedian();
stat.findMax();
stat.findMin();
// print the return values for each of the above out to the user
}
public static double[] readFile(double[] array, String fileName)
{
int valueCount = 0;
FileIO importFile = new FileIO ();
importFile.main(array, fileName);
System.out.println(array);
valueCount = array.length;
// return valueCount;
return array;
}
}
FileIO class:
import java.util.Scanner;
import java.io.*;
public class FileIO
{
public void main (double[] array, String fileName)
{
double [] num = new double[5];
Scanner inFile;
int i = 0;
try
{
System.out.println(fileName);
inFile = new Scanner(new File("fileName"));
while(inFile.hasNextDouble())
{
array[i] = inFile.nextDouble();
i++;
}
inFile.close();
for(int x = 0; x < i; x++)
System.out.println(" " + num[x]);
}
catch(FileNotFoundException e)
{
System.out.println (" File not found");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println (" array index too large");
}
}
}
Try by changing
inFile = new Scanner(new File("fileName"));
with
inFile = new Scanner(new File(fileName));
in the method FileIO.main
Other than that (having no link to the problem), you could make the method FileIO.main static, and take advantage of Java collections to avoid hardcoding the number of elements of the double you want to read from the file. In the same method you are declaring a variable double[] num but not using it at all.

Categories