File is not being made after I call my IO method - java

`public abstract class TV implements Logger {
protected int currentChannel;
protected int currentVolume;
protected String model;
public TV(String model)
{
this.model = model;
currentChannel = 2;
currentVolume = 10;
}
public void incChannel()
{
getcurrentChannel();
currentChannel = currentChannel + 1;
writeToLogFile("Increasing channel to " + currentChannel);
System.out.println("Increasing channel to " + currentChannel);
}
public void decChannel()
{
getcurrentChannel();
currentChannel = currentChannel - 1;
writeToLogFile("Decreasing channel to " + currentChannel);
System.out.println("Decreasing channel to " + currentChannel);
}
public void incVolume()
{
getcurrentVolume();
currentVolume = currentVolume + 1;
writeToLogFile("Increasing volume to " + currentVolume);
System.out.println("Increasing volume to " + currentVolume);
}
public void decVolume()
{
getcurrentVolume();
currentVolume = currentVolume - 1;
writeToLogFile("Decreasing volume to " + currentVolume);
System.out.println("Decreasing volume to " + currentVolume);
}
public void changeChannel(int currentChannel)
{
this.currentChannel = currentChannel;
writeToLogFile("Changing channel to " + currentChannel);
System.out.println("Changing channel to " + currentChannel);
}
public void writeToLogFile(String message)
{
model = getModel();
try {
FileReader fr = new FileReader(new File("./model.txt"));
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter(new File("./model.txt"), true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
String line = br.readLine();
while (line != null) {
Scanner scanLine = new Scanner(line);
String mess = scanLine.next();
pw.println(message);
pw.println(mess);
line = br.readLine();
}
br.close();
pw.flush();
pw.close();
}
catch (FileNotFoundException e)
{
System.out.println("File not found.");
}
catch (IOException e)
{
System.out.println("An IO error occurred.");
}
}`
When I call run my program my writeToLogFile method is not working correctly. When its called it is not making the text file as needed. I need the writeToLogFile method to create the file and then append it when its called in other methods.
Also, I have two models of TVs in this program. When I am using one of the TVs (Sony) I want it to write to its own log file named Sony.txt. I then have another TV (LG) that needs to have its own log file as well. Do I need to write two separate if statements to figure out the make of the tv then point it at its own log file?

The issue was with using the reader and writer on the same file at the same time. Once I got rid of the code where you open the file the method worked fine. I edited the code to reflect the proper changes.
I would guess there is a problem using a reader and a writer on the same file at the same time. I would recommend that you eliminate the reader and just open the file for append. Alternatively, you could open a different file for the writer, then once you're done writing to it, delete the original and rename your new file. – bcr666 6 mins ago

Related

Saving Game Scores

i am trying to make a highscore for a hangman game. So i need to save it so it doesnt restart everytime u start the game or return to the menu.. so I have a playstate that records the wins and losses at the end of the game and if the user leaves before solving it adds a loss. I found a tutorial to save via a SavaData file.. the problem is it saves an empty file nothing in there but has 2 empty lines.. and so i get a numberformatexception null.. i had it working before but it still would not read the line and would return an error numberformatexception Integer.parseInt.. I know the problem is in reading lines and now i dont know what went wrong please help me .. whats wrong with the code?? thanx
this is the saving code...
private void createSaveData() {
File file = new File(saveDataPath, filename);
try {
FileWriter output = new FileWriter(file);
BufferedWriter writer = new BufferedWriter(output);
writer.write("" + 0);
writer.newLine();
writer.write("" + 0);
} catch (Exception e) {
e.printStackTrace();
}
}
private void setScores() {
FileWriter output = null;
try {
File F = new File(saveDataPath, filename);
output = new FileWriter(F);
BufferedWriter writer = new BufferedWriter(output);
writer.write(wins);
writer.newLine();
writer.write(losses);
writer.close();
}catch (Exception e){
e.printStackTrace();
}
}
private void loadScores() {
try {
File F = new File(saveDataPath, filename);
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(F)));
String line = reader.readLine();
line = reader.readLine();
wins = Integer.parseInt(line);
line = reader.readLine();
losses = Integer.parseInt(line);
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
i then add loadScore(); at the begging of the playstate.. and setScore(); after a win++ or a loss++..
i have another highscorestate that calls on playstate and gets the wins and lossess as an integer and that works no problems cause it draws 0 , 0 .
in my render method i have this if the tries are too much or if the correct answer is guessed...
if (tries == 6) {
currentWord = ranWord;
execcurrentframe.setRegion(eman.ExecLoss.getKeyFrame(elapsedTime, false));
hangcurrentframe.setRegion(hman.hangdead.getKeyFrame(elapsedTime, false));
Wordsfont.draw(batch, "Game Over", eman.getPosition().x + 60, hman.getPosition().y + 70);
batch.draw(fu, 160, 510);
if (leverpressed == false){
bksound.stop();
lever.play();
leverpressed = true;
}
if (lossrecorded == false) {
losses += 1;
System.out.print("Losses = " + losses);
setScores();
lossrecorded = true;
}
}
else if (CorrectAnswer == true) {
hangcurrentframe.setRegion(hman.hangwin.getKeyFrame(elapsedTime, false));
Wordsfont.draw(batch, "You Won", eman.getPosition().x + 60, hman.getPosition().y + 70);
if (winrecorded == false) {
bksound.stop();
victory.play();
wins += 1;
System.out.print("Wins = " + wins);
setScores();
winrecorded = true;
}
}
I would suggest the following changes.
Use a single writeSaveData method. The code between createSaveData and setScores is largely duplicated. Also, use the Integer.toString() to write the output. Also, ensure the stream is closed (here using try with resources).
private void writeSaveData(int wins, int losses)
{
File file = new File(saveDataPath, filename);
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
writer.write(Integer.toString(wins));
writer.newLine();
writer.write(Integer.toString(losses));
}
catch (Exception e) {
e.printStackTrace();
}
}
There is an extra readLine() in the loadScores() method. Remove that extra line. Change to use try with resources.
private void loadScores()
{
File file = new File(saveDataPath, filename);
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)))) {
String line = reader.readLine();
// line = reader.readLine() <-- REMOVE THIS LINE
wins = Integer.parseInt(line);
line = reader.readLine();
losses = Integer.parseInt(line);
reader.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
EDIT: If one cannot use try with resources, then the following approach may be used instead.
private void loadScores()
{
File file = new File(saveDataPath, filename);
BufferedReader reader = null;
// try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)))) {
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line = reader.readLine();
wins = Integer.parseInt(line);
line = reader.readLine();
losses = Integer.parseInt(line);
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (reader != null) {
try {
reader.close();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
A similar modification may be made to the suggested writeSaveData() or other methods.
You have overlooked one important part of the original createSaveData method:
writer.write("" + 0);
See that "" + 0? It effectively converts the integer to a string (though there are more elegant ways of doing this).
BufferedWriter has overloaded write method. This means there is a different method that is called when the parameter is a String, and a different one when the parameter is an int.
You have called the version whose parameter is an int. Its documentation says:
public void write(int c) throws IOException
Writes a single character.
Overrides:
write in class Writer
Parameters:
c - int specifying a character to be
written
Throws:
IOException - If an I/O error occurs
This tells you that it considers the int that you passed as a character. That is, if you give it the int 65, it will be taken as the character A. If you give it the int 48, it will be taken as the character 0.
If you give it the integer 0, this is the NUL control character.
When you read that back as a string, it is taken as a single-character string containing the NUL character. Of course, that's not a valid string format for a number.
So replace
writer.write(wins);
With
writer.write(String.valueOf(wins));
And do the same for losses.

StackOverFlowError BufferedWriter issue

I'm programming a conversion tool that should take a json file as an input. Due to the problem that json input files may be very large I'll perform a split at the beginning. I have to resort the structure of the input file and because I don't want to keep the whole large file in my memory all the time, I'll split it.
I'm proofing the occurences of a json block by counting the { and }. If the counter is 0, a split should be performed. That's where the problem is: if the file is about 40MBs large the JVM throws a StackOverFlowError and I don't know why.
Here's what I do to perform a split:
/*
* Utility-function to read a json file part by part and save the parts to a separate json file.
* #param scanner The scanner which contains the file and which returns the lines from the file.
* #param j The counter of the file. As the file should change whenever the counter changes.
* #return jsonString The content of the jsonString.
*/
public String readPartOfFileAndSave(String filepath, Scanner scanner, int j) {
String jsonString = "";
int i = 0;
++j;
while (scanner.hasNext()) {
String token = scanner.next();
jsonString += token + System.lineSeparator();
if (token.contains("{")) {
i++;
}
if (token.contains("}")) {
i--;
}
if (i == 0) {
// DEBUG
// if (j % 1000 == 0) {
// System.gc();
// System.out.println("Garbage Collector called manually");
// }
saveFile(filepath, "actor", j, jsonString);
readPartOfFileAndSave(filepath, scanner, j);
}
}
return "";
}
/*
* #param filename The name of the target file where the content is saved to.
* #param j The counter of the file. As the file should change whenever the counter changes.
* #param content The content of the file.
*/
public void saveFile(String filepath, String fileprefix, int j, String content) {
File file = null;
if (this.osValidator.isWindows()) {
file = new File(filepath + "\\" + fileprefix + "" + j + ".json");
} else {
file = new File(filepath + "/" + fileprefix + "" + j + ".json");
}
try {
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file.getAbsoluteFile()), "UTF-8"));
bw.write(content);
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The exception looks like this:
Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError
at java.util.Hashtable.get(Hashtable.java:363)
at java.util.Properties.getProperty(Properties.java:969)
at java.lang.System.getProperty(System.java:717)
at sun.security.action.GetPropertyAction.run(GetPropertyAction.java:84)
at sun.security.action.GetPropertyAction.run(GetPropertyAction.java:49)
at java.security.AccessController.doPrivileged(Native Method)
at java.io.BufferedWriter.<init>(BufferedWriter.java:109)
at java.io.BufferedWriter.<init>(BufferedWriter.java:88)
at utility.ReadFileAndSave.saveFile(ReadFileAndSave.java:183)
at utility.ReadFileAndSave.readPartOfFileAndSave(ReadFileAndSave.java:158)
at utility.ReadFileAndSave.readPartOfFileAndSave(ReadFileAndSave.java:159)
splitFile() is called in a separate class. But nothing else happens there.
public void splitFile() {
try {
ReadFileAndSave reader = new ReadFileAndSave();
String jsonFilePath = this.converterView.sourceTextField.getText();
File jsonFile = new File(jsonFilePath);
Scanner scanner = new Scanner(new FileInputStream(jsonFile), "UTF-8");
int j = 0;
File newDir = null;
if (this.osValidator.isWindows()) {
newDir = new File(System.getProperty("user.home") + "\\temp\\");
} else {
newDir = new File(System.getProperty("user.home") + "/temp/");
}
if (!newDir.exists()) {
newDir.mkdir();
}
if (this.osValidator.isWindows()) {
reader.readPartOfFileAndSave(System.getProperty("user.home") + "\\temp\\", scanner, j);
} else {
reader.readPartOfFileAndSave(System.getProperty("user.home") + "/temp/", scanner, j);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(FilterController.class.getName()).log(Level.SEVERE, null, ex);
}
}
The input file has about 38.000 blocks in it. About 5.200 will be splitted to separate files. Then the exception is thrown.
The JVM seems to have a problem with the BufferedWriter. Does anyone know how to fix this issue?

Writing a 2D Array to a string, then to a .txt file - Java

I have a Method that calls a second method, the second method will:
Create any missing directories
Create a file
Decode a 2D String[] to a String (Not working)
Write content
Write the decoded String to the file with a header (Not working)
First method
public static boolean store(Exception exception, String[][] flags){
return storePrivate(exception, location, flags);
}
Second Method (Not all code just relevant code)
private static boolean storePrivate(Exception exception, String dir, String[][] flags){
String flag = "";
for(int i = 0; i >= flags.length; i++){
flag = flag + "" + flags[i][0] + ": " + flags[i][1] + "\n";
}
try {
File directory = new File(dir);
File file = new File(dir + id + ".txt");
if (!directory.exists()) {
directory.mkdirs();
}
file.createNewFile();
FileWriter filewriter = new FileWriter(file.getAbsoluteFile());
BufferedWriter writer = new BufferedWriter(filewriter);
if(flag != ""){
writer.write("Flags by Developer: ");
writer.write(flag);
}
writer.flush();
writer.close();
return true;
} catch (IOException e) {
return false;
}
}
Call to the first method
public static void main(String[] args) {
try {
test();
} catch (Exception e) {
// TODO Auto-generated catch block
ExceptionAPI.store(e, new String[][]{{"flag1", "Should be part of flag1"}, {"flag2", "this should be flag 2 contence"}});
}
}
public static void test() throws IOException{
throw new IOException();
}
I cant find why this won't work. I think it has to do with the second method, particularly
if(flag != ""){
writer.write("Flags by Developer: ");
writer.write(flag);
}
Thanks if anyone can help me.
Curlip
Try this if you want to just convert an array of strings into a single string:
String[] stringTwoD = //... I think this is a 1D array, and Sting[][] is a 2D, anyway
String stringOneD = "";
for (String s : stringTwoD)
stringOneD += s;//add the string with the format you want
BTW, your loop condition seems wrong and ,so you may change it to :
for(int i = 0; i < flags.length; i++){
flag += flags[i][0] + ": " + flags[i][1] + "\n";
}

unable to load file from my computers local directory to java program

i m trying to code for sorting strings,taking input from text file.When i m trying to specify a file for this program is gives me FileNotFoundExcetion
i m unable to understand why?
even i tried to get file path by writing code for that,in the screenShoot u can see that path is correct but the program is still giving me ERROR
here is thet Screenshort
https://app.box.com/s/qytu1d9xlm0vcb6atz42
here is my code
public static void main(String[] args) throws FileNotFoundException, IOException {
ArrayList<String> row1 = new ArrayList<>();
FileWriter writer;
try {
String filename = "1.txt";
String finalfile = "";
String workingDir = System.getProperty("user.dir");
String your_os = System.getProperty("os.name").toLowerCase();
if (your_os.indexOf("win") >= 0) {
finalfile = workingDir + "\\" + filename;
} else if (your_os.indexOf("nix") >= 0 || your_os.indexOf("nux") >= 0) {
finalfile = workingDir + "/" + filename;
} else {
finalfile = workingDir + "{others}" + filename;
}
System.out.println("Final filepath : " + finalfile);
File file = new File(finalfile);
if (file.createNewFile()) {
System.out.println("Done");
} else {
System.out.println("File already exists!");
}
} catch (IOException e) {
e.printStackTrace();
}
try (BufferedReader reader = new BufferedReader(new FileReader("finalfile"))) {
String s;
while ((s = reader.readLine()) != null) {
row1.add(s);
}
Collections.sort(row1);
writer = new FileWriter("output.txt");
for (String s1 : row1) {
writer.write(s1 + "\n");
}
reader.close();
writer.close();
} catch (Exception e) {
System.out.print("Error : " + e);
}
}
In
BufferedReader reader = new BufferedReader(new FileReader("finalfile")))
the parameter to the FileReader constructor is hard coded as "finalfile" - you need to use the variable instead:
BufferedReader reader = new BufferedReader(new FileReader(finalfile)))
^^^^^^^^^^^
You also need to move String finalfile = ""; before the first try block, otherwise it is out of scope when you are creating the FileReader.
Also, there is no need to query the operating system and manually set the directory path separator. If you really need to, use File.separator. Otherwise, simply use the forward slash - this is working cross-platform.
It is good to see that you are using try-with-resources - however, you should do it consequently; simply create all required resources in the try statement, and then there is no need to explicitly close them:
try (BufferedReader reader = new BufferedReader(new FileReader(finalfile));
FileWriter writer = new FileWriter("output.txt")) {
...
// reader and writer will be auto-closed
} catch (IOException e) {
System.out.print("Error : " + e);
}

losing data while writing through asynchronousFileChannel in java

I am trying to use asynchronousFileChannel to write the date into a text file. I made 3 jar file of the program with the AsynchronousFileChannel and compiled all 3 jars simultaneously through command prompt to read 3 different text files and output to one common temporary file
I have 2000 records in my test files(3) to be read,but the output in the common temporary file is missing some of the records,the output should have 6000 records but it shows only 5366 or 5666 or sometimes less than that.
I am not able to figure out why some data is lost as it is the functionality of a asynchronousFileChannel.
Here is the code for the java program using asynchronousfilechannel.
class Writer(){
public void writeOut(ReadableData fileData)
throws InterruptedException {
Path file = null;
AsynchronousFileChannel asynchFileChannel = null;
String filePath = tempFileName;
try {
file = Paths.get(filePath);
asynchFileChannel = AsynchronousFileChannel.open(file,
StandardOpenOption.WRITE, StandardOpenOption.CREATE);
CompletionHandler<Integer, Object> handler = new CompletionHandler<Integer, Object>() {
#Override
public void completed(Integer result, Object attachment) {
if (result == Integer.MAX_VALUE) {
log.debug("Attachment: " + attachment + " " + result
+ " bytes written");
log.debug("CompletionHandler Thread ID: "
+ Thread.currentThread().getId());
}
result++;
}
#Override
public void failed(Throwable e, Object attachment) {
try {
throw e;
} catch (Throwable e1) {
e1.printStackTrace();
}
log.debug("File Write Failed Exception:");
e.printStackTrace();
}
};
String printData = fileData.getId() + "|"
+ fileData.getName() + "|" + fileData.getEmpId()
+ "|" + fileData.getServieId() + "|" + "\n";
asynchFileChannel.write(ByteBuffer.wrap(printData.getBytes()),
asynchFileChannel.size(), "file write", handler);
log.debug(printData);
}
}
catch (IOException e) {
e.printStackTrace();
log.error(e.getMessage());
} finally {
}
}
}
}
and this is my class to read data from 3 files:
public class FileReader1 {
static Logger log = Logger.getLogger(FileHandlerNorthBoundMain.class
.getName());
Writer wrO=new Writer();
public static void main(String[] args) throws IOException,
IllegalFileFormatException, InterruptedException {
String filePath = "C:\\Users\\Public\\testdata1.csv"; //"C:\\Users\\Public\\testdata2.csv"; "C:\\Users\\Public\\testdata3.csv";
File file = new File(filePath);
log.info("Fetching data.... from: " + filePath);
ArrayList<ReadableData> list = new ArrayList<ReadableData>();
FileInputStream fs = null;
BufferedReader reader = null;
String Name;
int Id, EmpId, ServiceId;
ReadableData readableData = null;
int count = 0;
fs = new FileInputStream(file);
reader = new BufferedReader(new InputStreamReader(fs));
String line = reader.readLine();
while (line != null) {
StringTokenizer st = new StringTokenizer(line, "\\|");
while (st.hasMoreTokens()) {
try {
Id = Integer.parseInt(st.nextToken());
Name = st.nextToken();
EmpId = Integer.parseInt(st.nextToken());
ServiceId = Integer.parseInt(st.nextToken());
readableData = new ReadableData(Id,
, Name, EmpId,ServiceId);
wrO.writeOut(readableData);
list.add(count, readableData);
count = count++;
} catch (Exception ex) {
log.error("Illegal File Format");
throw new IllegalFileFormatException("Illegal File Format");
}
}
line = reader.readLine();
}
reader.close();
}
Modify your Writer class with the following code part with asynchronousFileChannel lock()
byte[] test = printData.getBytes();
Future<FileLock> featureLock = asynchFileChannel.lock();
log.info("Waiting for the file to be locked ...");
FileLock lock = featureLock.get();
if (lock.isValid()) {
log.debug(printData);
Future<Integer> featureWrite = asynchFileChannel.write(
ByteBuffer.wrap(test), asynchFileChannel.size());
log.info("Waiting for the bytes to be written ...");
int written = featureWrite.get();
log.info("I’ve written " + written + " bytes into "
+ file.getFileName() + " locked file!");
lock.release();
}
This might be because asynchronousFileChannel is thread safe but Bytebuffer is not,care should be taken to ensure that the buffer is not accessed until after the operation has completed.
check the documentation http://openjdk.java.net/projects/nio/javadoc/java/nio/channels/AsynchronousFileChannel.html

Categories

Resources