I am trying to create 4 index files using FileWriter. However this code throws Concurrent Modification Exception. I searched a few forums and found the use of finally as a solution, which dint work. Please tell me where can the error be.
public synchronized void writeToDisk() throws IndexerException {
// TODO Implement this method
BufferedWriter bw = null;
try {
//System.out.println("entering writeToDisk");
File file = new File("/Users/workspace/master/tmp//Index.txt");
if(IndexAuthor==-1){
file = new File("/Users/workspace/master/tmp/Author.txt");
if (!file.exists()) {
file.createNewFile();
}
}
if(IndexTerm==-1){
file = new File("/Users/workspace/master/tmp/Term.txt");
if (!file.exists()) {
file.createNewFile();
}
}
if(IndexCategory==-1){
file = new File("/Users/workspace/master/tmp/Category.txt");
if (!file.exists()) {
file.createNewFile();
}
}
if(IndexLink==-1){
file = new File("/Users/workspace/master/tmp/Link.txt");
if (!file.exists()) {
file.createNewFile();
}
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
bw = new BufferedWriter(fw);
bw.write(PostingsList.toString());
//bw.close();
//System.out.println("Done");
} catch (IOException e) {
//do nothing
}
finally
{
try {
if (bw == null)
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Related
Here's a program I've writing in Android Studio to write a CSV file.
I keep receiving the error "Cannot find symbol class".
I need help resolving that.
File fileDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "MyDir");
if (!fileDir.exists()) {
try {
fileDir.mkdir();
} catch (Exception e) {
e.printStackTrace();
}
}
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator +File.separator+"MyText.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
if (file.exists()) {
try {
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bfWriter = new BufferedWriter(fileWriter);
bfWriter.write("Text Data");
bfWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
If that is your complete program it can't compile because each file in Java needs to be a class and you didn't indicate it is a class. And if the class is to be invoked from the command line instead of just instantiated by another class, then you need to name your main entry point.
I've added those things, but have not compiled it. The compiler may generate other errors if the code isn't perfect.
See how that goes and then if you're still stuck update the question with more details and or ask a new more specific question. If this answer helps at all, please give it an up vote.
import java.io.*;
public class WriteCSV
{
public static void main(String args[])
{
File fileDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "MyDir");
if (!fileDir.exists()) {
try {
fileDir.mkdir();
} catch (Exception e) {
e.printStackTrace();
}
}
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator +File.separator+"MyText.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
if (file.exists()) {
try {
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bfWriter = new BufferedWriter(fileWriter);
bfWriter.write("Text Data");
bfWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
How does this code delete the file I had and makes a new one??
public void actualizaJTextArea(String cliente){
mensagens.setText("");
Scanner scanner = null;
File file = createFile(cliente + "chatswith.txt");
try {
scanner = new Scanner(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
(...)
scanner.close();
}
public static File createFile(String s){
File file = new File(s);
if(!file.exists()){
try {
boolean b = file.createNewFile();
System.out.println(b);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return file;
}
Does the method createNewFile() do this?
Thanks and I'm sorry if this has been asked before I just can't find it.
EDIT
I am also using createFile() in here to write in it but the use is the same so i guess that can't be it:
public void recebeMensagem(boolean b){
while(true){
Mensagem m = null;
try {
m = (Mensagem)input.readObject();
System.out.println("Mensagem Recebida:"+m);
} catch (ClassNotFoundException e){
} catch (IOException e) {
try {
input.close();
System.out.println("Server desligou...");
break;
} catch (IOException e1) {
}
}
if(m != null){
for(Mensagens mensagens:v){
for(String string: m.getReceivers()){
if (mensagens.getCliente().equals(m.getAuthor()) && mensagens.getContacto().equals(string)){
mensagens.actualizaJTextArea(cliente);
}
}
}
for(String Str :m.getReceivers()){
PrintWriter p = null;
File file = Mensagens.createFile(cliente + "chatswith.txt");
try {
p = new PrintWriter(new FileWriter(file));
p.append(m.getAuthor()+"</<"+Str+"</<"+m.getText()+"\n");
p.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
createNewFile() is atomic and it will not delete the file if it is present. Please look at the boolean output, it should be false if your file exists already.
EDIT
add append parameter to FileWriter. It is overwriting every time.
FROM
p = new PrintWriter(new FileWriter(file));
TO
p = new PrintWriter(new FileWriter(file,true));
using IOUtils.write to write a string to a file
try {
IOUtils.write("test", new FileWriter(configFile));
} catch (Exception e) {
e.printStackTrace();
}
where configfile is the location of the configuration file ("./resources/config.json")
This seems to delete the file and replace it with a file that has no contents.
no exceptions are thrown either.
Make sure to close the stream after use, else the data might not be written to the file.
FileWriter fw=null;
try {
fw= new FileWriter(configFile);
IOUtils.write("test",fw);
}catch (Exception e) {
e.printStackTrace();
}finally
{
IOUtils.closeQuietly(fw);
}
You need to close the writer, or use try with resources. Otherwise everything might not be flushed to disk:
try (FileWriter fw = new FileWriter(configFile)) {
IOUtils.write("test", fw);
} catch (IOException e) {
e.printStackTrace();
}
Try this code:
FileWriter fw = null;
try {
fw = new FileWriter(configFile);
IOUtils.write("test", fw);
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fw != null)
fw.close();
}
I have the following code to write in three files. I have printed the Strings before writing to ensure they have some data in them, the printed Strings show the data given to them by calling this function but on creation of file the files are empty.
Please suggest something.
public static void save(String editedFileText,String srcFileText,String translFileText)throws IOException {
JFileChooser chooser = new JFileChooser();
System.out.println(editedFileText);
System.out.println(srcFileText);
System.out.println(translFileText);
int retrival = chooser.showSaveDialog(null);
if (retrival == JFileChooser.APPROVE_OPTION) {
try {
FileWriter edit = new FileWriter(chooser.getSelectedFile()+".txt");
edit.write(editedFileText.toString());
FileWriter srcFile = new FileWriter(chooser.getSelectedFile()+"_srcText"+".txt");
srcFile.write(srcFileText.toString());
FileWriter trans = new FileWriter(chooser.getSelectedFile()+"_translFile"+".txt");
trans.write(translFileText.toString());
} catch (Exception ex) {
ex.printStackTrace();
}
}
Get in the habit of creating all Writers, Readers, InputStreams and OutputStreams in try-with-resources statements. It ensures they will be properly closed:
try (FileWriter edit = new FileWriter(chooser.getSelectedFile()+".txt")) {
edit.write(editedFileText);
}
try (FileWriter srcFile = new FileWriter(chooser.getSelectedFile()+"_srcText"+".txt")) {
srcFile.write(srcFileText);
}
try (FileWriter trans = new FileWriter(chooser.getSelectedFile()+"_translFile"+".txt")) {
trans.write(translFileText);
}
If you're just writing a single String, you have the option of using Files.write, which allows you to forego the use of a Writer altogether:
Files.write(Paths.get(chooser.getSelectedFile()+".txt"),
editedFileText.getBytes());
Files.write(Paths.get(chooser.getSelectedFile()+"_srcText"+".txt"),
srcFileText.getBytes());
Files.write(Paths.get(chooser.getSelectedFile()+"_translFile"+".txt"),
translFileText.getBytes());
Add a finally to close the opened files, but first you need to declare them outside the try catch finally:
FileWriter edit,srcFile, trans;
edit = srcFile = trans = null;
try {
edit = new FileWriter(chooser.getSelectedFile()+".txt");
edit.write(editedFileText.toString());
srcFile = new FileWriter(chooser.getSelectedFile()+"_srcText"+".txt");
srcFile.write(srcFileText.toString());
trans = new FileWriter(chooser.getSelectedFile()+"_translFile"+".txt");
trans.write(translFileText.toString());
} catch (Exception ex) {
ex.printStackTrace();
}finally{
if(edit != null)
edit.close();
if(srcFile != null)
srcFile.close();
if(trans != null)
trans.close();
}
FileWriter writer=null;
try {
writer = new FileWriter(filename);
writer.write(sb.toString());
} catch (Exception e) {
} finally {
if (writer != null)
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I have this code to write to a file when I add a user to an array list. The code works fine:
public void writeToFile(String content)
{
try {
File file = new File("H:/JavaWorkspace/TradingPlatformProject/User_Report.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content + "\n" );
bw.close();
logger.info("Recorded to User Activity file");
} catch (IOException e) {
e.printStackTrace();
}
}
I want to write to a separate file when a user does something differently (say, request a permission upgrade). Is there any way I can write to a new file "UserRequests.txt" without duplicating this code?
Why not make the method more general?
public void writeToFile(String content, String fileName, String path)
{
try {
File file = new File(path + fileName);
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content + "\n" );
bw.close();
logger.info("Recorded to User Activity file");
} catch (IOException e) {
e.printStackTrace();
}
}
Then you could use the method for writing all kinds of files :3
You should probably just use a 2nd argument, as in the following.
Moreover, you should close your Writers in a finally block. That way, you would be sure that the Writers are closed even if a exception occurred while writing.
public void writeToFile(String content, String path)
{
FileWriter fw
BufferedWriter bw
try {
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
}
fw = new FileWriter(file.getAbsoluteFile(), true);
bw = new BufferedWriter(fw);
bw.write(content + "\n" );
bw.close();
logger.info("Recorded to User Activity file");
} catch (IOException e) {
e.printStackTrace();
} finally {
bw.close();
fw.close();
}
}
I would just pass in the file you want to write to:
public void writeToFile(String content, String filename){
And then:
File file = new File("H:/JavaWorkspace/TradingPlatformProject/"+filename);