I'm trying to create a file that maps every possible binary combination of some part of speech tags, and for some reason the java program I've written just stops after 8192 bytes. I assume that this is the maximum buffer size or something? How can I change that?
My code:
try {
Scanner in = new Scanner(new FileInputStream(file.getPath()));
PrintWriter out = new PrintWriter(new FileOutputStream("S2.gr"));
createS2(in, out);
} catch (Exception e) {
System.out.println("There was an error trying to open the files: " + e.getMessage());
}
private static void createS2(Scanner in, PrintWriter out) {
String[] pos = in.useDelimiter("\\A").next().split("\\n");
out.println("1\tS2");
for (String x : pos) {
out.println("1\tS2\t_" + x);
}
for (String x : pos) {
String temp = ("1\t_" + x + "\t" + x);
out.println(temp);
for (String y : pos) {
out.println(temp + " _" + y);
}
}
for (String x : pos) {
System.out.println(x);
}
}
Try this...
Scanner in = null;
PrintWriter out = null;
try {
in = new Scanner(new FileInputStream(file.getPath()));
out = new PrintWriter(new FileOutputStream("S2.gr"));
createS2(in, out);
} catch (Exception e) {
System.out.println("There was an error trying to open the files: " + e.getMessage());
}
finally {
if(in != null) in.close();
if(out != null) out.close();
}
Note: if you're using Java 7, there's a new feature to make this easier. e.g.
try (Scanner in = new Scanner(new FileInputStream(file.getPath()));
PrintWriter out = new PrintWriter(new FileOutputStream("S2.gr")))
{
createS2(in, out);
} catch (Exception e) {
System.out.println("There was an error trying to open the files: " + e.getMessage());
}
Note: I don't have a JDK 7 available to me at the moment, so the second example might not be 100% correct, but the idea is that the new language feature can manage closing resources for you.
Related
public static void componiPoesia(String outputFile, String[] frasi) {
try (PrintWriter pw = new PrintWriter(
new FileOutputStream(new File(outputFile), true))) {
int count = 0;
for (String frase : frasi) {
pw.print(frase + ". ");
count++;
pw.print("\n" + count);
}
pw.close();
} catch (IOException e) {
System.out.println("Error writing into the outputFile: " + outputFile);
e.printStackTrace();
}
}
*This is what should come out
ChiHaRobaInMareNonHaNulla. TuttiIPiuGrandiPensieriSonoConcepitiMentreSiCammina.
2, 1
This is what comes out of me
ChiHaRobaInMareNonHaNulla.
1TuttiIPiuGrandiPensieriSonoConcepitiMentreSiCammina.
2
try this one, As your code pw.print("\n" + count); brek your line so i make it outside loop and done some changes in your code for expecting output.
try (PrintWriter pw = new PrintWriter( new FileOutputStream(new File(outputFile), true))) {
int count = 0;
String temp="";
for (String frase : frasi) {
pw.print(frase + ". ");
if(count==0)
temp=(frasi.length-count)+"";
else
temp=temp+","+(frasi.length-count);
count++;
}
pw.print("\n" + temp);
pw.close();
} catch (IOException e) {
//System.out.println("Error writing into the outputFile: " + outputFile);
e.printStackTrace();
}
According to the expected output, I suppose, that you have to print the phrases to the file (from the String[] frasi array) in the for each loop and count the number of phrases. You don't have to print counter in for-each loop. After the loop you can do something like:
while(counter > 0)
{
pw.print(counter);
counter--;
if(counter > 0)
pw.print(", ");
}
Im working on converter. I load file, start reading date from it and creating directories by year, month and day(+ another one dir) in witch ends are those converted text files. Everything is fine while creating those directories but in text files is nothing or only chunk of it.
public static void convertFile(File fileToConvert, File whereToSave, long shift) {
BufferedReader reader = null;
BufferedWriter writer = null;
String oldDate = "";
String newDate = "";
boolean boolDate = true;
try {
for (File file : fileToConvert.listFiles()) {
reader = new BufferedReader(new FileReader(file));
boolean block = true;
String line = "";
int lineCounter = 0;
while ((line = reader.readLine()) != null) {
if (lineCounter==0) {
block = true;
} else {
block = false;
}
line = line.replaceAll("[^0-9-,:+NaN.]", "");
String[] data = line.split(",");
if (block) {
data[0] = data[0].substring(0, 10) + " " + data[0].substring(10);
data[0] = SimulatorForRealData.timeShift(data[0], shift);
// ====================================================================================
newDate = data[0].substring(0, 4) + " " + data[0].substring(5, 7) + " "
+ data[0].substring(8, 10);
String savingIn = SimulatorForRealData.createDirs(whereToSave.toString(),
data[0].substring(0, 4), data[0].substring(5, 7), data[0].substring(8, 10));
File f = new File(savingIn + "\\" + FILE_NAME + ".log");
if (!newDate.equals(oldDate) && boolDate == false) {
writer.close();
boolDate = true;
} else {
oldDate = newDate;
boolDate = false;
}
writer = new BufferedWriter(new FileWriter(f));
// =====================================================================================
writer.write("<in date=\"" + data[0].substring(0, 10) + "T" + data[0].substring(11)
+ "\" t=\"1\" >\n");
writer.write(data[0] + "\n");
writer.write(0 + " " + 0 + " " + 0 + "\n");
for (int x = 0; x <= 10; x++) {
writer.write("NaN" + " ");
}
writer.write("\n");
for (String s : data) {
if (s.equals(data[0])) {
continue;
}
writer.write(s + ";");
}
writer.write("\n");
} else {
for (String s : data) {
writer.write(s + ";");
}
writer.write("\n");
}
lineCounter++;
if (lineCounter == 118) {
lineCounter = 0;
writer.write("</in>\n\n");
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
writer.close();
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here is method where i perform it. Can someone help me. I tried different "writers" and nothing. I have suspicious that it will be problem in closing file but i dont know for sure.
I think you should close every writer you created, not only last one.
for (File file : fileToConvert.listFiles()) {
reader = new BufferedReader(new FileReader(file));
...
writer = new BufferedWriter(new FileWriter(f));
while ((line = reader.readLine()) != null) {
....
}
writer.close();
}
writer flushes all changes on disk only when buffer is overflowed or it is closed.
I see two main problems:
You create a file every time you read a line. You should put it outside the loop (or loops, if you want only one file)
Always data is written with the same filename. It should have different filenames if you make a file for every file read.
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.
I have a little problem with making a java command for program i have some code but i do not know how to continue i stuck in one place BTW the command i want to make is /sendcash [username] [money] // how it looks like
I have this code:
if (cmd.equals(AdminCommands[1])) {
String player = scanner.next();
int money = scanner.nextInt();
File folder = new File(player);
File pFile = new File(folder, player + ".txt");
File bFile = new File(folder, money + ".txt");
if (pFile.exists() && bFile.exists()) {
try {
Account pAcc = new Account(player, money);
if(pAcc.admin != 1) {
try {
writer = new BufferedWriter(new FileWriter(bFile));
writer.write(player);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
writer.close();
} catch (Exception e) {
}
}
LabelInfo.setText("Money transfer complited ! ( " + money + " ) to ( " + pAcc.name + " )");
} else {
LabelInfo.setText("You can't transfer money to an admin!");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Username doesn't exist!");
}
}
}
EDIT Now with this code nothing happening in the console and in the files too i dont know what to do here is the code in the class Account
public Account(String player, int cash) {
this.username = player;
this.money = cash;
}
If you mean by transfer the money to write the result into files, you can do it like this:
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(pFile));
writer.write(player);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
writer.close();
} catch (Exception e) {
}
}
Problem solved i actually have missed something in the constructor class Account and also can somebody explain me why with the brackets in writer.write(""+cashTransfer); are not showing the characters like ✐, 蚠, etc.. for example when i will put in [cash] field 100 its shows me the letter d and so on ...
Here is the whole working code...
if (cmd.equals(AdminCommands[1])) {
String playerUsername = scanner.next();
int cashTransfer = scanner.nextInt();
File folder = new File(playerUsername);
File pFile = new File(folder, playerUsername + ".txt");
File bFile = new File(folder, "balance.txt");
if (pFile.exists()) {
try {
Account pAcc = new Account(playerUsername, cashTransfer);
FileWriter bWriter = new FileWriter(bFile);
BufferedWriter writer;
writer = new BufferedWriter(bWriter);
writer.write(""+cashTransfer);
pAcc.SaveInfo();
writer.close();
LabelInfo.setText("Money transfer complited ! ( $" + cashTransfer + " ) to ( " + pAcc.username + " )");
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "ERROR: Can't save balance !");
}
} else {
LabelInfo.setText("Player not found !");
}
}
BTW Thank you #Salah for helping me !!! :)
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