Write data to an external file in Java - java

I have data in my BufferedReader, but I want to print the data in an external file.
How do I do that?
URL url=new URL(input);
BufferedReader br=new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
while((inputLine=br.readLine())!=null)
System.out.println(inputLine);
br.close();
The above code works for me. Instead, I want to save the data in an external file.

URL url=new URL(input);
BufferedReader br=new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
BufferedWriter writer = Files.newBufferedWriter(Paths.get(""));
while ((inputLine = br.readLine()) != null) {
System.out.println(inputLine);
writer.write(inputLine);
// must do this: .readLine() will have stripped line endings
writer.newLine();
}
writer.close();
br.close();

If i have understood correctly you have your data and you want to write them in an external txt file.
String path1 = "Your Path File";
File file1 = new File(path1);
file1.createNewFile();
FileWriter fw = new FileWriter(file1);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("\n"+ your data); // "\n" because the new data will overwrite the previous
//and it will be lost
bw.flush();
FileReader fr = new FileReader(file1);
BufferedReader br = new BufferedReader(fr);
br.close();
bw.close();

Related

Java Writer stopping after single write

I'm looking to read the contents of a URL and write them to file, this is working as expected but it's only writing it a single time even though the program console shows multiple lines.
Code:
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
while(true) {
URL oracle = new URL("https://linkToData.com");
BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
writer.println(inputLine);
System.out.println(inputLine);
}
writer.close();
The data in the URL refreshes constantly so there should be different data each time as the console print shows but it's only writing the first instance to file.
The key is writer.close()! If you want to write the file anew every time, you have to reopen the Writer each time.
If you want to append file each time you have to flush writer instead of closing and close at the end.
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
while(condition) {
URL oracle = new URL("https://linkToData.com");
BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
writer.println(inputLine);
System.out.println(inputLine);
}
writer.flush();
}
writer.close();

How can I print every line available from one BufferedReader before checking another BufferedReader?

PrintWriter out = new PrintWriter(DoDSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(DoDSocket.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser;
while ((fromServer = in.readLine()) != null)
{
System.out.println(fromServer);
if ((fromUser= stdIn.readLine()) != null)
{
//System.out.println(fromUser);
out.println(fromUser);
}
}
In this code for a client, I've created a Print Writer and a buffered reader which communicate with a Server, I also have a separate reader which reads the System.in from the command line.
My problem at the moment is that if the server send the client a multi line string, I will have to press enter to receive each line. How can I edit this code so that every line is printed from the buffered reader from the server, before it checks what the user has typed, rather than checking after every individual line?
Why not do one loop after the other?:
PrintWriter out = new PrintWriter(DoDSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(DoDSocket.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser;
while ((fromServer = in.readLine()) != null)
{
System.out.println(fromServer);
}
while ((fromUser = stdIn.readLine()) != null)
{
System.out.println(fromUser);
}

JCIFS: is possible get a file and use like BufferedReader?

I've a method that returns a BufferedReader, something like this:
File file = new File(fileName);
try {
BufferedReader br = new BufferedReader(new FileReader(file));
}
catch(FileNotFoundException ex){
ex.getStackTrace();
}
How can I get a file with JCIFS API and return a BufferedReader?
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(file), "UTF-8"));

Reading InputStream as UTF-8

I'm trying to read from a text/plain file over the internet, line-by-line. The code I have right now is:
URL url = new URL("http://kuehldesign.net/test.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
LinkedList<String> lines = new LinkedList();
String readLine;
while ((readLine = in.readLine()) != null) {
lines.add(readLine);
}
for (String line : lines) {
out.println("> " + line);
}
The file, test.txt, contains ¡Hélló!, which I am using in order to test the encoding.
When I review the OutputStream (out), I see it as > ¬°H√©ll√≥!. I don't believe this is a problem with the OutputStream since I can do out.println("é"); without problems.
Any ideas for reading form the InputStream as UTF-8? Thanks!
Solved my own problem. This line:
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
needs to be:
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
or since Java 7:
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8));
String file = "";
try {
InputStream is = new FileInputStream(filename);
String UTF8 = "utf8";
int BUFFER_SIZE = 8192;
BufferedReader br = new BufferedReader(new InputStreamReader(is,
UTF8), BUFFER_SIZE);
String str;
while ((str = br.readLine()) != null) {
file += str;
}
} catch (Exception e) {
}
Try this,.. :-)
I ran into the same problem every time it finds a special character marks it as ��. to solve this, I tried using the encoding: ISO-8859-1
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("txtPath"),"ISO-8859-1"));
while ((line = br.readLine()) != null) {
}
I hope this can help anyone who sees this post.
If you use the constructor InputStreamReader(InputStream in, Charset cs), bad characters are silently replaced. To change this behaviour, use a CharsetDecoder :
public static Reader newReader(Inputstream is) {
new InputStreamReader(is,
StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT)
);
}
Then catch java.nio.charset.CharacterCodingException.

java: how to convert a file to utf8

i have a file that have some non-utf8 caracters (like "ISO-8859-1"), and so i want to convert that file (or read) to UTF8 encoding, how i can do it?
The code it's like this:
File file = new File("some_file_with_non_utf8_characters.txt");
/* some code to convert the file to an utf8 file */
...
edit: Put an encoding example
The following code converts a file from srcEncoding to tgtEncoding:
public static void transform(File source, String srcEncoding, File target, String tgtEncoding) throws IOException {
BufferedReader br = null;
BufferedWriter bw = null;
try{
br = new BufferedReader(new InputStreamReader(new FileInputStream(source),srcEncoding));
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(target), tgtEncoding));
char[] buffer = new char[16384];
int read;
while ((read = br.read(buffer)) != -1)
bw.write(buffer, 0, read);
} finally {
try {
if (br != null)
br.close();
} finally {
if (bw != null)
bw.close();
}
}
}
--EDIT--
Using Try-with-resources (Java 7):
public static void transform(File source, String srcEncoding, File target, String tgtEncoding) throws IOException {
try (
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(source), srcEncoding));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(target), tgtEncoding)); ) {
char[] buffer = new char[16384];
int read;
while ((read = br.read(buffer)) != -1)
bw.write(buffer, 0, read);
}
}
String charset = "ISO-8859-1"; // or what corresponds
BufferedReader in = new BufferedReader(
new InputStreamReader (new FileInputStream(file), charset));
String line;
while( (line = in.readLine()) != null) {
....
}
There you have the text decoded. You can write it, by the simmetric Writer/OutputStream methods, with the encoding you prefer (eg UTF-8).
You need to know the encoding of the input file. For example, if the file is in Latin-1, you would do something like this,
FileInputStream fis = new FileInputStream("test.in");
InputStreamReader isr = new InputStreamReader(fis, "ISO-8859-1");
Reader in = new BufferedReader(isr);
FileOutputStream fos = new FileOutputStream("test.out");
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
Writer out = new BufferedWriter(osw);
int ch;
while ((ch = in.read()) > -1) {
out.write(ch);
}
out.close();
in.close();
You only want to read it as UTF-8?
What I did recently given a similar problem is to start the JVM with -Dfile.encoding=UTF-8, and reading/printing as normal. I don't know if that is applicable in your case.
With that option:
System.out.println("á é í ó ú")
prints correctly the characters. Otherwise it prints a ? symbol

Categories