-1

I am trying to build a program in JAVA that takes data from a URL and saves it to a text file. My main problem is that my program doesn't store line changes. To be more specific here is my code:

import java.io.*;
import java.net.*;

public class Jva_Parser {
    public static void main(String[] args) throws Exception {

        URL oracle = new URL("http://cgi.di.uoa.gr/~std10108/a.txt");
        BufferedReader in = new BufferedReader(
        new InputStreamReader(oracle.openStream()));
        PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");

        String inputLine;
        while ((inputLine = in.readLine()) != null)
        {
            writer.write(inputLine+"\n");               
            System.out.println(inputLine);
        }
        writer.close();
        in.close();
    }
}

The ouput at the console is:

This is a message!

This is a second line!

as it should be. The file is exactly this. Whereas the file that is created, contains this:

This is a message!This is a second line!

I cannot understand what I am doing wrong.

EDIT: I tried this but it doesn't works either

writer.write(inputLine + System.getProperty( "line.separator" ));

Yes I open the file with notepad, and I am at windows. I want to take the program to android so any further information would be usefull

JmRag
  • 1,443
  • 7
  • 19
  • 56

3 Answers3

3

You are probably verifying this using something ala notepad yes? These programs will not display the line change because you have only got \n, which may not be the system line separator. Try appending System.getProperty( "line.separator" ) rather than just \n (probably \n\r on your system)

Sinkingpoint
  • 7,449
  • 2
  • 29
  • 45
0

System.getProperty( "line.separator" ) is the right approach so that it can work on all the platforms correctly.

FileUtils.copyURLToFile from apache provides the same. You should try that. http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#copyURLToFile(java.net.URL, java.io.File)

gmansoor
  • 509
  • 1
  • 4
  • 12
0

I prefer PrintWriter because of this situation

PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");

    String inputLine;
    while ((inputLine = in.readLine()) != null)
    {
        writer.println(inputLine);               
        System.out.println(inputLine);
    }

Might need this instead, its typically how I create my writer:

PrintWriter out = new PrintWriter(new FileWriter("the-file-name.txt"));

I call it "out", so that I can insert or delete System. for logging purposes. I use a command like replace all System.out. with out. Or to put it back, out.println with System.out.println

Dan Ciborowski - MSFT
  • 6,807
  • 10
  • 53
  • 88