This code:
PrintWriter output = new PrintWriter(new FileWriter(outputFile, false));
output.println("something\n");
output.println("something else\n");
Outputs:
something
something else
Instead of:
something
something else
I tried using "\r\n" instead of just "\n" but it just doesn't work like how I want it to. How do I fix this?
P.S. I'm using windows 7
You can concatenate system's newline to separate your lines:
String newLine = System.getProperty("line.separator");
output.println("something" + newLine);
output.println("something else" + newLine);
Your code works like a charm, just check the file with a proper programmers editor.
(or as I suggested before, take a look at an hex dump of the file)
This
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class Main {
public static void main(String[] args) {
PrintWriter output;
try {
output = new PrintWriter(new FileWriter("asdf.txt", false));
output.println("something\n");
output.println("something else\n");
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Works well for me, I get an asdf.txt like this
something
something else
I am using jre1.7, what are you using?
This works perfectly fine. You must be using notepad for the output. Try using a different text editor like notepad++. You'll get your desired output.
Try this:
package com.stackoverflow.works;
import java.io.FileWriter;
import java.io.PrintWriter;
/*
* #author: sarath_sivan
*/
public class PrintWriterExample {
private static final String NEW_LINE = System.getProperty("line.separator");
public static void main(String[] args) {
String outputFile = "C:/Users/sarath_sivan/Desktop/out.txt";
PrintWriter output = null;
try {
output = new PrintWriter(new FileWriter(outputFile, false));
output.println("something" + NEW_LINE);
output.println("something else" + NEW_LINE);
output.flush();
} catch(Exception exception) {
exception.printStackTrace();
} finally {
if (output != null) {
output.close();
}
}
}
}
OUTPUT:
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I have a method where I create a new instance of PrintWriter:
public class Clazz {
File temp = new File("temp.txt");
private void saveInTempFile(String text) {
try (
PrintWriter pw = new PrintWriter(new FileWriter(temp, true));
) {
pw.write("text: " + text + '\n');
pw.close();
} catch (IOException e) {
System.out.println("An error occurred.");
}
}
}
Now, I need to call this method at various points in my program and I want to add a new line (with the variable text) to the temp file. However, at this state, it only writes into the file the first time I call this method. I have tried it both with and without pw.close(); with no difference.
I need a new line to be added every time I call this method, yet only the first line is added.
It doesn't strictly have to be done using PrintWriter nor FileWriter
I would very appreciate any help, please.
Like I use the following (I don't find it efficient).
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import java.io.File;
public class Clazz {
protected PrintWriter out;
private String outFileName;
private String prefix = "";
public Clazz(){
this.outFileName = "test";
}
private void createOutput(String outFileName) {
try {
this.out = new PrintWriter(new FileWriter(outFileName));
} catch (IOException e) {
System.out.println("Couldn't open file '" + outFileName );
// "' for report output\n" + e.getMessage(), e);
}
}
protected void write(String txt) {
if (out == null) {
createOutput(outFileName);
}
out.println(prefix + txt);
}
public void done() {
if (out != null) {
out.close();
}
}
public static void main( String[] args){
Clazz obj = new Clazz();
String output = "hi 1\n";
obj.write(output);
String output2 = "hello 2\n ";
obj.write(output2);
obj.done();
}
}
I know this topic has been discussed a lot and I have already read a lot of posts here about that, but I still seem to have trouble.
My problem is that I am also a beginner and I don't really understand how ĸwork and the try and catch function.
I have been trying to write to a file some string array, but it doesn't appear in there, nor the catch error is displayed in the console. I don't want to use the try method in this case, because when I am, I cannot use the variable declared for let's say BufferedWriter in other places, I am only restricted to the try method. Otherwise, I get a bug.
This is my code:
import java.io.*;
import java.util.*;
import java.lang.*;
public class FileWrit {
public static void main (String[] args){
try(BufferedWriter writer = new BufferedWriter(new FileWriter("testing.txt"))) {
String[] anything = new String[3];
writer.write("anything");
anything[0] = "case1";
anything[1] = "This is 1.5";
anything[2] = "Case 3, i do not know how to count";
for(String mem: anything) {
writer.append(mem);
}
writer.close();
} catch(IOException e) {
System.err.println("Idk when should this appear?");
}
}
}
For the "can't use it anywhere" part of your problem, you could declare the variable outside of the try catch block and only assign it inside. You can do a null check wherever else you want to use it to make sure there's no problems, or assign it another value in the catch block. Like so:
public static void main(String[] args) {
BufferedWriter writer;
String[] anything;
try {
writer = new BufferedWriter(new FileWriter("testing.txt"))) {
anything = new String[3];
writer.write("anything");
anything[0] = "case1";
anything[1] = "This is 1.5";
anything[2] = "Case 3, i do not know how to count";
for (String mem: anything) {
writer.append(mem);
}
writer.close();
} catch (IOException e) {
writer = null;
e.printstacktrace();
}
}
}
if(writer != null){
System.out.println(writer);
}
try and catch it's use for managed the exception. try this code:
import java.io.*;
import java.util.*;
import java.lang.*;
public class FileWrit {
public static void main (String[] args){
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("testing.txt"))
String[] anything = new String[3];
writer.write("anything");
anything[0] = "case1";
anything[1] = "This is 1.5";
anything[2] = "Case 3, i do not know how to count";
for(String mem: anything) {
writer.append(mem);
}
writer.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
The System.err.println("Idk when should this appear?"); appear when you have an Exception in your try "an Error".
I wrote a very simple piece of code, It was working perfectly since yesterday but now not working and even after lots of research/debugging i have not got the issue
import java.net.InetAddress;
import java.util.Date;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
public class DetectLoggedInUser{
public static void returnUserName()
{
String computerName;
try {
File file =new File("d:\\TestFolder\\UsersloggedIn.txt");
if(!file.exists()){
file.createNewFile();
}
FileWriter fileWritter = new FileWriter(file.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
String content= "\n UserName="+System.getProperty("user.name")+ " || Date and Time= "+new Date();
bufferWritter.write(content);
bufferWritter.close();
}
catch(Exception ex) {
ex.printStackTrace();
}
}
public static void main(String args[])
{
returnUserName();
}
}
Now file is created but nothing is being written in file
Is there anything wrong with this code(keeping in mind it was working since yesterday)?
Try this:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Date;
public class DetectLoggedInUser {
public static void returnUserName() {
try {
File file = new File("d:\\TestFolder\\UsersloggedIn.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fileWritter = new FileWriter(file, true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
String content = "\n UserName=" + System.getProperty("user.name")
+ " || Date and Time= " + new Date();
bufferWritter.write(content);
bufferWritter.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String args[]) {
returnUserName();
}
}
You can use
FileWriter fileWritter = new FileWriter(file.getAbsolutePath(), true);
Instead of file.getName() in your code.File.getName() method returns only the name of the file or directory,not the absolute path;
You don't need to check if the files exists or not, beside that it works fine for me.
I have 3 class to handle all configs. (2000 lines in 2 class)
And I want add support to UTF-8 chars without writing all code from 0 ;/
I show my smallest class (is not finished and I don't want to spam with 1400 lines :))
Have actual only two variables:
package com.gmail.bukkitSmerf.professionalWarns;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
public class LangHandler {
private static String lWarns_DeletedWarnAddon, lWarns_ExpiredWarnAddon;
public static String getlWarns_DeletedWarnAddon() {
return lWarns_DeletedWarnAddon;
}
public static String getlWarns_ExpiredWarnAddon() {
return lWarns_ExpiredWarnAddon;
}
public void createConfig(boolean forceConfigUpdate) {
try {
String langFileName = "languageEN.yml";
InputStream input = ProfessionalWarns
.getPluginResource_languageEN();
if (ConfigHandler.getcGeneral_Language().equalsIgnoreCase("PL")) {
langFileName = "languagePL.yml";
input = ProfessionalWarns.getPluginResource_languagePL();
}
File langFile = new File(ProfessionalWarns.getPluginDataFolder(),
langFileName);
if (!langFile.exists()) {
langFile.getParentFile().mkdirs();
ConfigHandler.copy(input, langFile);
}
YamlConfiguration lang = new YamlConfiguration();
FileConfiguration rawLang = YamlConfiguration
.loadConfiguration(input);
lang.load(langFile);
lWarns_DeletedWarnAddon = lang.getString("Warns.DeletedWarnAddon",
rawLang.getString("Warns.DeletedWarnAddon"));
lWarns_ExpiredWarnAddon = lang.getString("Warns.ExpiredWarnAddon",
rawLang.getString("Warns.ExpiredWarnAddon"));
if (ConfigHandler.iscGeneral_AutoUpdateConfigs()
|| forceConfigUpdate) {
FileWriter fw = new FileWriter(langFile);
PrintWriter pw = new PrintWriter(fw);
pw.flush();
pw.write("Warns:\n DeletedWarnAddon: '"
+ lWarns_DeletedWarnAddon + "'\n ExpiredWarnAddon: '"
+ lWarns_ExpiredWarnAddon + "'");
pw.close();
}
} catch (IOException | InvalidConfigurationException e) {
e.printStackTrace();
ProfessionalWarns
.logWarning("Error when trying create/write/reload language file!");
}
}
}
I don't have idea how to use that UTF-8 here.
I also don't want delete any features.
If you can, give me also some advices about that code :)
//Sorry for my English
Based on your comment, I'm going to blame your use of FileWriter:
FileWriter fw = new FileWriter(langFile);
This relies on your installation's default encoding, which I'm willing to bet is not UTF-8. You can verify this with the following:
System.out.println(Charset.defaultCharset());
Regardless, the correct way to write UTF-8 characters to a file is to use an OutputStreamWriter:
FileOutputStream fos = new FileOutputStream("your_file");
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
PrintWriter pw = new PrintWriter(osw);
And unless this is one-off code, you should close the FileOutputStream in a finally block.
I'm writing a little program that just takes a file, and trims the last 4 characters after a space and writes those to a new file. When I tell it to do this and then print them to console it works fine. They show up fine and everything works. But when I use the BufferedWriter to write it to a new file it gives me a weird string of characters in that file when I check it. Here is my code:
package trimmer;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class trimmer {
private File file;
private File newfile;
private Scanner in;
public void Create() {
String temp, temp1;
try {
setScanner(new Scanner(file));
} catch (FileNotFoundException e) {
System.out.println("file not found!!");
}
if (!newfile.exists()) {
try {
newfile.createNewFile();
FileWriter fw = new FileWriter(newfile.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
while (in.hasNextLine()) {
temp1 = in.nextLine();
temp = temp1.substring(temp1.lastIndexOf(' ') + 1);
System.out.println(temp);
bw.write(temp);
}
bw.close();
System.out.println("done!");
} catch (IOException e) {
System.out.println("Could not make new file: " + newfile + " Error code: " + e.getMessage());
}
}
}
public Scanner getScanner() {
return in;
}
public void setScanner(Scanner in) {
this.in = in;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public File getNewfile() {
return newfile;
}
public void setNewfile(File newfile) {
this.newfile = newfile;
}
}
and when I check the file it looks like this:
䐳噔吳商吳啍唳噎吳剄唳剄䘳剄唳噎吳商䠳卉䌳䕎䜳䱁䠳卉䴳㉕倳乓䐳䍐䐳啐吳䍖吳乓吳啍䔳䥘䌳噔匳剕唳乓唳䅍䌳䕎䜳䱁䴳㉕倳乓䐳䍐䐳啐吳䍖䠳卉吳乓吳啍䔳䥘䌳噔匳剕唳乓唳䅍
Can anyone tell me why this would be happening?
FileWriter uses the platform default character encoding. If this is not the encoding that you want, then you need to use an OutputStreamWriter with the appropriately chosen character encoding.