How to write ArrayList data to text file in java - java

I m trying to write ArrayList data in to the Text file using this code:
public PrintWriter w() {
try {
FileWriter f = new FileWriter("C:\\Users\\jon\\Desktop\\a.txt");
PrintWriter br = new PrintWriter(f);
return br;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
return null;
}
for (String g : a) {
try {
PrintWriter br = w();
br.println(g);
System.out.print(" " + g);
} catch (Exception e1) {
JOptionPane.showMessageDialog(null, e1);
}
But it is not writing the data to the text file. Can anyone help me see the problem?

Here it is:
public static BufferedWriter w() throws IOException{
File file = new File("D:\\filename.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
return bw;
}
and this is what you need to call from your for loop:
for (String g : a) {
try {
BufferedWriter bw = w();
bw.write(g);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}

Related

FileSystemException even after closing buffers

I have this problem java.nio.file.FileSystemException: The process cannot access the file because it is being used by another process. and I can't understand why. The System.err.println(e.getFile()); says the file that causing the exception is the groupFile, but I close the Buffers before using it with the closeBuffers().
what could be the problem with my code?
File groupFile = getFile(_grp +File.separator+ mensagem.getGroup().getName()+".txt");
ServerLogHandler group2SLH = linkHandlerToFile(groupFile);
if(group2SLH.getGroupAdmin().equals(mensagem.getUser().getName())){
try{
File temp = createFile(_grp +File.separator+"temp.txt");
group2SLH.closeBuffers();
deleteAndWrite(membro2.getName(), groupFile, temp);
Files.move(temp.toPath(), groupFile.toPath(), REPLACE_EXISTING);
temp.delete();
}catch(FileSystemException e){
System.err.println(e.getFile());
e.printStackTrace();
}
}
public void closeBuffers(){
try {
this.in.close();
this.out.flush();
this.out.close();
} catch (IOException e) {
System.err.println(e.getMessage());
e.printStackTrace();
}
}
public static void deleteAndWrite(String deleteThis, File in, File out){
try {
BufferedReader in2 = new BufferedReader(new FileReader(in));
BufferedWriter out2 = new BufferedWriter(new FileWriter(out, true));
String s;
StringBuilder sb = new StringBuilder();
while((s = in2.readLine()) != null){
if(!s.equals(deleteThis)){
sb.append(s+System.getProperty("line.separator"));
out2.write(sb.toString());
}
}
in2.close();
out2.close();
} catch (IOException e) {
e.printStackTrace();
}
}

Making Java I / O and change the file to split in java

I'm making a project where using java I / O
I have a file with the following data:
170631|0645| |002014 | 0713056699|000000278500
155414|0606| |002014 | 0913042385|000001220000
000002|0000|0000|00000000000|0000000000000000|000000299512
and the output I want is as follows:
170631
0645
002014
file so that the data will be decreased down
and this is my source code:
public class Tes {
public static void main(String[] args) throws IOException{
File file;
BufferedReader br =null;
FileOutputStream fop = null;
try {
String content = "";
String s;
file = new File("E:/split/OUT/Berhasil.RPT");
fop = new FileOutputStream(file);
br = new BufferedReader(new FileReader("E:/split/11072014/01434.RPT"));
if (!file.exists()) {
file.createNewFile();
}
while ((s = br.readLine()) != null ) {
for (String retVal : s.split("\\|")) {
String data = content.concat(retVal);
System.out.println(data.trim());
byte[] buffer = data.getBytes();
fop.write(buffer);
fop.flush();
fop.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I want is to generate output as above from the data that has been entered
File Input -> Split -> File Output
thanks :)
I think you forgot to mention what problem are you facing. Just by looking at the code it seems like you are closing the fop(FileOutputStream) every time you are looping while writing the split line. The outputStream should be closed once you have written everything, outside the while loop.
import java.io.*;
public class FileReadWrite {
public static void main(String[] args) {
try {
FileReader inputFileReader = new FileReader(new File("E:/split/11072014/01434.RPT"));
FileWriter outputFileWriter = new FileWriter(new File("E:/split/11072014/Berhasil.RPT"));
BufferedReader bufferedReader = new BufferedReader(inputFileReader);
BufferedWriter bufferedWriter = new BufferedWriter(outputFileWriter);
String line;
while ((line = bufferedReader.readLine()) != null) {
for (String splitItem : line.split("|")) {
bufferedWriter.write(splitItem + "\n");
}
}
bufferedWriter.flush();
bufferedWriter.close();
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Writing to a file in Java. Help me code

I am passing a file path to this method which writes the in txt file. But when I run this program it is not writing full and I don't know where I made mistake.
public void content(String s) {
try {
BufferedReader br=new BufferedReader(new FileReader(s));
try {
String read=s;
while((read = br.readLine()) != null) {
PrintWriter out = new PrintWriter(new FileWriter("e:\\OP.txt"));
out.write(read);
out.close();
}
} catch(Exception e) { }
} catch(Exception e) { }
}
You shouldn't create your PrintWriter inside the loop every time:
public void content(String s) {
BufferedReader br=new BufferedReader(new FileReader(s));
try {
PrintWriter out=new PrintWriter(new FileWriter("e:\\OP.txt"));
String read=null;
while((read=br.readLine())!=null) {
out.write(read);
}
} catch(Exception e) {
//do something meaningfull}
} finally {
out.close();
}
}
Aditionally, as others have mentioned add a finally block, do not silently catch the exception, and follow the Java Coding Conventions.
close your PrintWriter inside finally block out side the loop
finally {
out.close();
}
It's better to use Apache Commons IO instead.
http://commons.apache.org/io/api-release/org/apache/commons/io/IOUtils.html should make the trick.
(Unless you are trying to learn the low-level stuff or actually knows why you can't use IOUtils for this case.)
try this
public void content(String s) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(s));
PrintWriter pr = new PrintWriter(new File("e:\\OP.txt"))) {
for (String line; (line = br.readLine()) != null;) {
pr.println(line);
}
}
}
Your closing stream before finishing it. So either put it into
<code>
finally {
out.close();
}
</code>
or see this simple example
<code>try {
String content = s;
File file = new File("/filename.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
</code>

Java webpanel commands not saving

I have a java app that gets commands from a webpanel, and when it executes a command, it saves somewhere so that it knows that it has executed already. then when it next executes a command, it checks the list before executing the command, this works fine one a PC, but on a mac, it seems to not work.
it saves the commands, but when it checks for new commands, it executes all previous commands aswell.
n3.data contains:
1,2,3,4,
each command is given an id (in this case 1 2 3 and 4), the app is supposed to check what command ids it has used and then execute if the id is not in the specified file (n3.data)
here is the code.
public void save(int id) {
String osName = System.getProperty("os.name");
if(osName.contains("Windows")){
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(System.getProperty("user.home") + "\\app.data", true));
bw.write(id + ",");
bw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
} else if(osName.contains("Mac")){
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(System.getProperty("user.home") + "/n3.data", true));
bw.write(id + ",");
bw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public void createNew() {
String osName = System.getProperty("os.name");
File win = new File(System.getProperty("user.home") + "\\app.data");
File mac = new File(System.getProperty("user.home") + "/n3.data");
if(osName.contains("Windows") && !win.exists()){
try {
new File(System.getProperty("user.home") + "\\app.data").createNewFile();
} catch (IOException ex) {
ex.printStackTrace();
}
}else if(osName.contains("Mac") && !mac.exists()){
try {
new File(System.getProperty("user.home") + "/n3.data").createNewFile();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public void saveNew() {
String osName = System.getProperty("os.name");
if(osName.contains("Windows")){
StringBuilder sb = new StringBuilder();
for (int i : processedIds) {
sb.append(i + ",");
}
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(System.getProperty("user.home") + "\\app.data"));
bw.write(sb.toString());
bw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}else if(osName.contains("Mac")){
StringBuilder sb = new StringBuilder();
for (int i : processedIds) {
sb.append(i + ",");
}
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(System.getProperty("user.home") + "/n3.data"));
bw.write(sb.toString());
bw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public void loadSave() throws IOException {
String osName = System.getProperty("os.name");
if(osName.contains("Windows")){
File file = new File(System.getProperty("user.home") + "\\app.data");
if (file.exists()) {
BufferedReader br = new BufferedReader(new FileReader(file));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
for (String s : sb.toString().split(",")) {
try {
processedIds.add(Integer.parseInt(s));
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
file.createNewFile();
}
}else if(osName.contains("Mac")){
File file = new File(System.getProperty("user.home") + "/n3.data");
if (file.exists()) {
BufferedReader br = new BufferedReader(new FileReader(file));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
for (String s : sb.toString().split(",")) {
try {
processedIds.add(Integer.parseInt(s));
} catch (Exception e) {
e.printStackTrace();
}
}
} else if (!file.exists()){
file.createNewFile();
}
}
}
I figured it out, anyone having the same problem, the code doesn't check properly if the file exists or not. just fix that and it should work.

Java: PrintWriter

I am trying to use PrintWriter.java but I am getting a rather strange problem and I am not able to figure out what am I am missing here.
MyPrintWriter.java
public class MyPrintWriter {
public static void main(String[] args) {
File myFile = new File("myFileDirectory/myFileName.txt");
try {
FileWriter fw = new FileWriter(myFile);
PrintWriter pw = new PrintWriter(fw);
pw.println("Hello World!");
pw.close();
} catch (FileNotFoundException e) {
System.err.println("File not found: " + myFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
MyFileWriter.java
public class MyFileWriter {
public static void main(String[] args) {
File myFile = new File("myFileDirectory/myFileName.txt");
try {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
FileWriter fw = new FileWriter(myFile);
PrintWriter pw = new PrintWriter(fw);
String input;
input = br.readLine();
while(input != null) {
pw.println(input);
input = br.readLine();
}
br.close();
pw.close();
} catch (FileNotFoundException e) {
System.err.println("File not found: " + myFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
MyPrintWriter.java is happily writing to the myFileName.txt file but MyFileWrite.java can't.
Could someone help me understand what am I missing here?
You probably need to flush your print writer.
The PrintWriter constructor with a FileWriter parameter creates a PrintWriter with autoFlush set to off
Calling pw.flush() before pw.close(); should do the trick

Categories