Java - How to write ArrayList Objects into txt file? - java

/** I have some methods likes add,display,sort,delete,and exit that implemented the ArrayList function. It works correctly, but the problem is that the objects that had been added were not saved on a .txt file, just the temporary objects. So I need to add them into text file,so that I can display and delete them later. Here's the part of the codes.
*/
public class testing {
public static void main(String[] args) {
String Command;
int index = 0;
Scanner input = new Scanner(System.in);
ArrayList<String> MenuArray = new ArrayList<String>();
boolean out = false;
while (!out) {
System.out.print("Enter your Command: ");
Command = input.nextLine();
// method ADD for adding object
if (Command.startsWith("ADD ") || Command.startsWith("add ")) {
MenuArray.add(Command.substring(4).toLowerCase());
// indexing the object
index++;
/** i stuck here,it won't written into input.txt
BufferedWriter writer = new BufferedWriter(new FileWriter(
"input.txt"));
try {
for (String save : MenuArray) {
int i = 0;
writer.write(++i + ". " + save.toString());
writer.write("\n");
}
} finally {
writer.close();
}*/
} else if (Command.startsWith("EXIT") || Comand.startsWith("exit")) {
out = true;
}
}
}
}

FileUtils#writeLines seems to do exactly what you need.

You can use ObjectOutputStream to write an object into a file:
try {
FileOutputStream fos = new FileOutputStream("output");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(MenuArray); // write MenuArray to ObjectOutputStream
oos.close();
} catch(Exception ex) {
ex.printStackTrace();
}

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

How to check if txt file contains a String, if so don't duplicate it

So right now I'm making a mod in Minecraft where it takes everyones username from a server and adds it to a txt file, it works but the the problem is I don't want to duplicate the names when I use the command again. Nothing has worked so far. How would I check if the txt already contains the username, don't add it again? Thank you. Again, I need it to before writing another name to the list, check the txt file if it already contains the name, if so don't add it.
for (int i = 0; i < minecraft.thePlayer.sendQueue.playerInfoList.size(); i++) {
List playerList = minecraft.thePlayer.sendQueue.playerInfoList;
GuiPlayerInfo playerInfo = (GuiPlayerInfo) playerList.get(i);
String playerName = StringUtils.stripControlCodes(playerInfo.name);
try {
fileWriter = new FileWriter(GameDirectory() + "\\scraped.txt", true);
bufferedReader = new BufferedReader(new FileReader(GameDirectory() + "\\scraped.txt"));
lineNumberReader = new LineNumberReader(new FileReader(GameDirectory() + "\\scraped.txt"));
} catch (IOException e) {
e.printStackTrace();
}
printWriter = new PrintWriter(fileWriter);
try {
fileWriter.write(playerName + "\r\n");
lineNumberReader.skip(Long.MAX_VALUE);
} catch (IOException e) {
e.printStackTrace();
}
printWriter.flush();
}
addMessage("Scraped " + lineNumberReader.getLineNumber() + " usernames!");
EDIT: Really need an answer guys :( Thank you
EDIT: this is what I have now, but it's not even writing it anymore.
List playerList = minecraft.thePlayer.sendQueue.playerInfoList;
for (int i = 0; i < minecraft.thePlayer.sendQueue.playerInfoList.size(); i++) {
GuiPlayerInfo playerInfo = (GuiPlayerInfo) playerList.get(i);
String playerName = StringUtils.stripControlCodes(playerInfo.name);
String lines;
try {
if ((lines = bufferedReader.readLine()) != null) {
if (!lines.contains(playerName)) {
bufferedWriter.write(playerName);
bufferedWriter.newLine();
bufferedWriter.flush();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
int linenumber = 0;
try {
while (lineNumberReader.readLine() != null) {
linenumber++;
}
} catch (IOException e) {
e.printStackTrace();
}
The logic of your second piece of code is wrong. If you write out the pseudo-code of it, it's easy to see why:
Open a File Reader at the start of the file
For every Player on the server
Save the player name
Read the next line of the file
If we have not reached the end of the file
If the player name is not on this line of the file
Write the name of the player to the file
You need to read the entire file outside of the loop, and then check if the player exists anywhere in the file, not just if it happens to be on the line which is the same position as the player on the server.
The easiest way to do this is to keep the players in a list while you're processing, and read/write them to file, like this:
public static List<String> loadPlayerList() throws FileNotFoundException
{
final Scanner scanner = new Scanner(new File(GameDirectory() + "\\scraped.txt"));
final List<String> players = new ArrayList<>();
while(scanner.hasNextLine())
players.add(scanner.nextLine());
return players;
}
public static void writePlayersList(final List<String> players) throws IOException
{
try(final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream((GameDirectory() + "\\scraped.txt")))))
{
for(final String player : players)
{
writer.write(player);
writer.newLine();
}
}
}
public static void main(String[] args) throws IOException
{
final List<String> players = loadPlayerList();
for(final GuiPlayerInfo player : minecraft.thePlayer.sendQueue.playerInfoList)
{
final String playerName = StringUtils.stripControlCodes(player.name);
if(!players.contains(playerName))
players.add(playerName);
}
writePlayersList(players);
}

Saving Stats with Java IO

I have a file and a basic reader and writer set up but when I change the value it doesn't write the new value
Here's the code:
int constitutionLevel, strengthLevel;
int[] saveStats = { constitutionLevel, strengthLevel };
int constitutionLevelLocation = 0;
int strengthLevelLocation = 1;
public StatSaver()
{
constitutionLevel = Constitution.getConstitutionLevel();
strengthLevel = Strength.getStrengthLevel();
}
public void startSaving()
{
readPlayer("SaveManagement/Stats/save.txt");
updatePlayerStats();
savePlayer("SaveManagement/Stats/save.txt");
}
private void updatePlayerStats()
{
System.out.println("Saving Stats...");
System.out.println(constitutionLevel);
constitutionLevel = saveStats[constitutionLevelLocation];
strengthLevel = saveStats[strengthLevelLocation];
System.out.println(constitutionLevel);
System.out.println("Done Saving Stats");
}
private void readPlayer(String filePath)
{
File inputFile;
BufferedReader inputReader;
try
{
inputFile = new File(filePath);
inputReader = new BufferedReader(new FileReader(inputFile));
for (int i = 0; i < saveStats.length; i++)
{
saveStats[i] = Integer.parseInt(inputReader.readLine());
}
inputReader.close();
} catch (Exception e) { e.printStackTrace(); }
}
private void savePlayer(String filePath)
{
File outputFile;
BufferedWriter outputWriter;
try
{
outputFile = new File(filePath);
outputWriter = new BufferedWriter(new FileWriter(outputFile));
outputWriter.write(saveStats[0] + "\n");
outputWriter.write(saveStats[1] + "\n");
//for (int i = 0; i < saveStats.length; i++)
//{
// outputWriter.write(saveStats[i] + "\n");
//}
outputWriter.close();
} catch (Exception e) { e.printStackTrace(); }
}
As you can see I have a line of code commented out but the two lines of code right above do the same thing I just have to type a few more things, I could change it for something bigger but since I have two stats right now I am not in any rush. The only solution that is short term would be to change the value in the .txt file but that would not work when I public the game because everybody would put the stat at infinity. Anyways please help and Thanks in advance!
So, in your startSaving() method, you read in information from readPlayer() (which I assume is the old values stored in the file), and then place the values into the array. In the updatePlayerStats(), you take the values in the array, and put them into the two variables (overwriting what was placed in them by the constructor). Lastly, the savePlayer() method takes the information from the array, and saves them into the file. At no point did you change the values in the array, so no new numbers are being added to the file.

writing in text file in java

I have a text file that contained a large number of words, and i want to divide the words by writing ** for every 4 words.
What i did until now is adding the first ** ( the first 4 words) and I have some difficulties in putting the other stars.
here is my code until now (I am using java)
import java.io.*;
public class Insert {
public static void main(String args[]){
try {
INSERT In = new INSERT();
int tc=4;
In.insertStringInFile (new File("D:/Users//im080828/Desktop/Souad/project/reduction/weight/outdata/d.txt"), tc, "**");
}
catch (Exception e) {
e.printStackTrace();
}
}
public void insertStringInFile(File inFile, int lineno, String lineToBeInserted)
throws Exception {
// temp file
File outFile = new File("$$$$$$$$.tmp");
// input
FileInputStream fis = new FileInputStream(inFile);
BufferedReader in = new BufferedReader
(new InputStreamReader(fis));
// output
FileOutputStream fos = new FileOutputStream(outFile);
PrintWriter out = new PrintWriter(fos);
String thisLine = "";
int i =1;
while ((thisLine = in.readLine()) != null) {
if(i == lineno) out.println(lineToBeInserted);
out.println(thisLine);
i++;
}
out.flush();
out.close();
in.close();
inFile.delete();
outFile.renameTo(inFile);
}
}
Please.. give me some ideas
Thanks :)
When you do if (i == lineno) you only get true if (i==4), so your behavior is normal. You need to use the modulo operator if ((i % lineno) == 0) to get a star every for lines.
http://www.dreamincode.net/forums/topic/273783-the-use-of-the-modulo-operator/

How to append data to a file?

I trying to write into the txt file.
But with out losing the data that is already stored in the file.
But my problem that when I put string in the txt file, the new string overwrite on the old string that i put it before.
My code is:
public void addWorker(Worker worker){
workers.put(worker.getId(), worker);
}
public void printWorker (String id){
Worker work = (Worker) workers.get( id );
if (work == null) {
System.out.println("Worker NOT found");
}
else {
work.printText();
}
}
public void printWorkers() {
if (workers.size() == 0) {
System.out.println("No workres");
return;
}
Collection<Worker> c = workers.values();
Iterator<Worker> itr = c.iterator();
System.out.println("Workers in division "+dName+ ":");
while (itr.hasNext()) {
Worker wo = itr.next();
wo.printText();
}
}
public void writeToFile(){
PrintWriter pw = null;
try{
pw = new PrintWriter(new File("d:\\stam\\stam.txt"));
Collection<Worker> c = workers.values();
Iterator<Worker> itr = c.iterator();
while (itr.hasNext()) {
Worker wo = itr.next();
pw.write("worker: "+wo.getId()+", "+wo.getName()+", "+wo.getAddress()+", "+wo.getSex());
pw.println();
}
}
catch(Exception e) {
System.out.println(e);
}
finally {
if (pw != null) {
pw.close();
}
}
}
}
Can you help me?
You have to set the Stream to append mode like this:
pw = new PrintWriter(new FileWriter("d:\\stam\\stam.txt", true));
Use a FileWriter with second argument 'true' and a BufferedWriter:
FileWriter writer = new FileWriter("outFile.txt", true);
BufferedWriter out = new BufferedWriter(writer);
Create a separate variable to emphasize that, appending to file.
boolean append = true;
pw = new PrintWriter(new FileWriter(new File("filepath.txt"), append));
In Java 7,
Files.write(FileSystems.getDefault().getPath(targetDir,fileName),
strContent.getBytes(),StandardOpenOption.CREATE,StandardOpenOption.APPEND);

Categories