Write to text file without overwriting in Java

前端 未结 9 1328
失恋的感觉
失恋的感觉 2020-11-30 05:02

I am trying to write a method that makes a \"log.txt file\" if one does not already exist and then writes to the file. The problem that I am encountering is every time I cal

相关标签:
9条回答
  • 2020-11-30 05:40
    JFileChooser c= new JFileChooser();
    c.showOpenDialog(c);
    File write_file = c.getSelectedFile();
    String Content = "put here the data to be wriiten";
    try
        {
        FileWriter fw = new FileWriter(write_file);
        BufferedWriter bw = new BufferedWriter(fw);
        bw.append(Content);
        bw.append("hiiiii");
        bw.close();
        fw.close();
        }
    catch(Exception e)
       {
        System.out.println(e);
       `}
    
    0 讨论(0)
  • 2020-11-30 05:41

    try this one

    public void writeFile(String arg1,String arg2) {
    		try {
    			if (!dir.exists()) {
    
    				if (dir.mkdirs()) {
    
    					Toast.makeText(getBaseContext(), "Directory created",
    							Toast.LENGTH_SHORT).show();
    				} else {
    					Toast.makeText(getBaseContext(),
    							"Error writng file " + filename, Toast.LENGTH_LONG)
    							.show();
    				}
    			}
    
    			else {
    
    				File file = new File(dir, filename);
    				if (!file.exists()) {
    					file.createNewFile();
    				}
    				
    				FileWriter fileWritter = new FileWriter(file, true);
    				BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
    				bufferWritter.write(arg1 + "\n");
    				bufferWritter.close();
    
                } catch (Exception e) {
    			e.printStackTrace();
    			Toast.makeText(getBaseContext(),
    					"Error writng file " + e.toString(), Toast.LENGTH_LONG)
    					.show();
    		}
    
    	}

    0 讨论(0)
  • 2020-11-30 05:47
    BufferedWriter login = new BufferedWriter(new FileWriter("login.txt"));
    

    is an example if you want to create a file in one line.

    0 讨论(0)
提交回复
热议问题