I have a problem of writing the UTF-8 character that cannot be properly read by Excel. When I open the excel, some characters are read as "Ņӊഎ«". I understand this is something to do the UTF BOM. Is there someone who how can help to explain me this?
Here are my codes for writing the CSV.
public class FileWriter {
private static String filenameTemp;
public static boolean creatFile(String name) throws IOException {
boolean flag = false;
filenameTemp = name + "";
System.out.println("write to file: "+filenameTemp);
File filename = new File(filenameTemp);
if (!filename.exists()) {
filename.createNewFile();
flag = true;
}
else {
filename.delete();
filename.createNewFile();
flag = true;
}
return flag;
}
public static boolean writeFile(String newStr) throws IOException {
boolean flag = false;
String filein = newStr + "\r\n";
String temp = "";
FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader br = null;
FileOutputStream fos = null;
PrintWriter pw = null;
try {
File file = new File(filenameTemp);
fis = new FileInputStream(file);
isr = new InputStreamReader(fis);
br = new BufferedReader(isr);
StringBuffer buf = new StringBuffer();
for (int j = 1; (temp = br.readLine()) != null; j++) {
buf = buf.append(temp);
buf = buf.append(System.getProperty("line.separator"));
}
buf.append(filein);
fos = new FileOutputStream(file);
byte[] unicode = {(byte)0xEF, (byte)0xBB, (byte)0xBF};
fos.write(unicode);
pw = new PrintWriter(fos);
pw.write(buf.toString().toCharArray());
pw.flush();
flag = true;
} catch (IOException e1) {
throw e1;
} finally {
if (pw != null) {
pw.close();
}
if (fos != null) {
fos.close();
}
if (br != null) {
br.close();
}
if (isr != null) {
isr.close();
}
if (fis != null) {
fis.close();
}
}
return flag;
}
Related
i would like to save in a string multiple lines from reading file, eg: I am reading one file.txt with the following content:
def var x as int.
def var y as char.
procedure something:
//here some content
end.
I would like to catch content between "procedure" and "end".
public static void main(String[] args) {
String piContent = "";
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
String line;
while ((line = br.readLine()) != null) {
if(line.contains("procedure")){
piContent = line;
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
I appreciate any help.
final StringBuilder sb = new StringBuilder();
try (final BufferedReader br = Files.newBufferedReader(file.toPath(), StandardCharsets.UTF_8)) {
String line;
boolean rememberStuff = false;
while ((line = br.readLine()) != null) {
if (line.startsWith("procedure ")) {
rememberStuff = true;
} else if (line.startsWith("end.")) {
rememberStuff = false;
} else if (rememberStuff) {
sb.append(line).append('\n');
}
}
} catch (IOException e) {
e.printStackTrace();
}
System.err.println("Lines found between procedure and end:");
System.err.println(sb);
public static String getContentFromFile(Path file) throws IOException {
StringBuilder buf = new StringBuilder();
boolean add = false;
for (String line : Files.readAllLines(file)) {
if ("end.".equalsIgnoreCase(line.trim()))
break;
if (add)
buf.append(line).append(System.lineSeparator());
else if ("procedure something:".equalsIgnoreCase(line.trim()))
add = true;
}
return buf.toString();
}
I'm trying to webget some bz2 files from Wikipedia, I don't care whether they are save as bz2 or unpacked, since I can unzip them locally.
When I call:
public static void getZip(String theUrl, String filename) throws IOException {
URL gotoUrl = new URL(theUrl);
try (InputStreamReader isr = new InputStreamReader(new BZip2CompressorInputStream(gotoUrl.openStream())); BufferedReader in = new BufferedReader(isr)) {
StringBuffer sb = new StringBuffer();
String inputLine;
// grab the contents at the URL
while ((inputLine = in.readLine()) != null) {
sb.append(inputLine + "\r\n");
}
// write it locally
Wget.createAFile(filename, sb.toString());
} catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
throw ioe;
}
}
I get a part of the unzipped file, never more than +- 883K.
When I don't use the BZip2CompressorInputStream, like:
public static void get(String theUrl, String filename) throws IOException {
try {
URL gotoUrl = new URL(theUrl);
InputStreamReader isr = new InputStreamReader(gotoUrl.openStream());
BufferedReader in = new BufferedReader(isr);
StringBuffer sb = new StringBuffer();
String inputLine;
// grab the contents at the URL
while ((inputLine = in.readLine()) != null) {
sb.append(inputLine);// + "\r\n");
}
// write it locally
Statics.writeOut(filename, false, sb.toString());
} catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
throw ioe;
}
}
I get a file of which the size is the same as it suppose to (compared to the KB not B). But also a message that that the zipped file is damaged, also when using byte [] instead of readLine(), like:
public static void getBytes(String theUrl, String filename) throws IOException {
try {
char [] cc = new char[1024];
URL gotoUrl = new URL(theUrl);
InputStreamReader isr = new InputStreamReader(gotoUrl.openStream());
BufferedReader in = new BufferedReader(isr);
StringBuffer sb = new StringBuffer();
// grab the contents at the URL
int n = 0;
while (-1 != (n = in.read(cc))) {
sb.append(cc);// + "\r\n");
}
// write it locally
Statics.writeOut(filename, false, sb.toString());
} catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
throw ioe;
}
}
Finally, when I bzip2 the inputstream and outputstream, I get a valid bzip2 file, but of the size like the first one, using:
public static void getWriteForBZ2File(String urlIn, final String filename) throws CompressorException, IOException {
URL gotoUrl = new URL(urlIn);
try (final FileOutputStream out = new FileOutputStream(filename);
final BZip2CompressorOutputStream dataOutputStream = new BZip2CompressorOutputStream(out);
final BufferedInputStream bis = new BufferedInputStream(gotoUrl.openStream());
final CompressorInputStream input = new CompressorStreamFactory().createCompressorInputStream(bis);
final BufferedReader br2 = new BufferedReader(new InputStreamReader(input))) {
String line = null;
while ((line = br2.readLine()) != null) {
dataOutputStream.write(line.getBytes());
}
}
}
So, how do I get the entire bz2 file, in either bz2 format or unzipped?
A bz2 file contains bytes, not characters. You can't read it as if it contained characters, with a Reader.
Since all you want to do is download the file and save it locally, all you need is
Files.copy(gotoUrl.openStream(), Paths.get(fileName));
I have looked around on how to do this and I keep finding different solutions, none of which has worked fine for me and I don't understand why. Does FileReader only work for local files? I tried a combination of scripts found on the site and it still doesn't quite work, it just throws an exception and leaves me with ERROR for the variable content. Here's the code I've been using unsuccessfully:
public String downloadfile(String link){
String content = "";
try {
URL url = new URL(link);
URLConnection conexion = url.openConnection();
conexion.connect();
InputStream is = url.openStream();
BufferedReader br = new BufferedReader( new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
content = sb.toString();
br.close();
is.close();
} catch (Exception e) {
content = "ERROR";
Log.e("ERROR DOWNLOADING",
"File not Found" + e.getMessage());
}
return content;
}
Use this as a downloader(provide a path to save your file(along with the extension) and the exact link of the text file)
public static void downloader(String fileName, String url) throws IOException {
File file = new File(fileName);
url = url.replace(" ", "%20");
URL website = new URL(url);
if (file.exists()) {
file.delete();
}
if (!file.exists()) {
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(fileName);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
}
}
Then call this function to read the text file
public static String[] read(String fileName) {
String result[] = null;
Vector v = new Vector(10, 2);
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(fileName));
String tmp = "";
while ((tmp = br.readLine()) != null) {
v.add(tmp);
}
Iterator i = v.iterator();
result = new String[v.toArray().length];
int count = 0;
while (i.hasNext()) {
result[count++] = i.next().toString();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return (result);
}
And then finally the main method
public static void main(){
downloader("D:\\file.txt","http://www.abcd.com/textFile.txt");
String data[]=read("D:\\file.txt");
}
try this:
try {
// Create a URL for the desired page
URL url = new URL("mysite.com/thefile.txt");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
StringBuilder sb = new StringBuilder();
while ((str = in.readLine()) != null) {
// str is one line of text; readLine() strips the newline character(s)
sb.append(str );
}
in.close();
String serverTextAsString = sb.toString();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
Error at
bw.write(dataString);
How can i fix this?
dataString cannot be resolved to a variable.
public class test {
public static void main(String[] args){
ArrayList<String> data = new ArrayList<String>();
try (BufferedReader br = new BufferedReader(new FileReader("src/test.txt"))) {
String CurrLine;
while((CurrLine = br.readLine()) != null) {
data.add(CurrLine);
}
String[] dataArray = new String[data.size()];
String dataString = Arrays.toString(dataArray);
String[] client = dataString.split("<::>");
Integer nameId = Arrays.binarySearch(client, "Test");
Integer versId = nameId + 1;
System.out.println(client[nameId] + "\n" + client[versId]);
} catch(FileNotFoundException ex) {
System.out.println("FNFE");
} catch(IOException ex) {
System.out.println("IOE");
}
try{
File file = new File("src/test.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(dataString);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
DeclaredataString outside of the try and catch block... Thats all. ;) If you declare it inside a loop or in this case your try catch block, its lifecycle is limited to it.
Like this:
String dataString = null;
and inside the try-catch block:
dataString = Arrays.toString(dataArray);
dataString is out of scope in the try block.
Perhaps add dataString as an instance variable at the top of your class.
public class test {
private String dataString = null;
public static void main(String[] args){
ArrayList<String> data = new ArrayList<String>();
try (BufferedReader br = new BufferedReader(new FileReader("src/test.txt"))) {
String CurrLine;
while((CurrLine = br.readLine()) != null) {
data.add(CurrLine);
}
String[] dataArray = new String[data.size()];
dataString = Arrays.toString(dataArray);
...
The dataString variable's scope is limited to the first try-catch block. Change its declaration as following,
public static void main(String[] args){
ArrayList<String> data = new ArrayList<String>();
String dataString = null;
try (BufferedReader br = new BufferedReader(new FileReader("src/test.txt"))) {
String CurrLine;
while((CurrLine = br.readLine()) != null) {
data.add(CurrLine);
}
String[] dataArray = new String[data.size()];
dataString = Arrays.toString(dataArray);
String[] client = dataString.split("<::>");
Integer nameId = Arrays.binarySearch(client, "Test");
Integer versId = nameId + 1;
System.out.println(client[nameId] + "\n" + client[versId]);
} catch(FileNotFoundException ex) {
System.out.println("FNFE");
} catch(IOException ex) {
System.out.println("IOE");
}
try{
File file = new File("src/test.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(dataString);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
i'm trying to read a web address from a text and then have the app open that address, my buffered reader seems to be reading the lines correctly but readline keeps coming back null
String rsslink = null;
InputStream is = getResources().openRawResource(R.raw.xmlsource);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((rsslink = br.readLine()) != null)
{
}
}
catch (IOException e)
{
e.printStackTrace();
}
String RSS_LINK = rsslink;
Log.d(Constants.TAG, "Service started");
List<RssItem> rssItems = null;
try
{
XMLRssParser parser = new XMLRssParser();
rssItems = parser.parse(getInputStream(RSS_LINK));
You will get the last line that is null rsslink.
You need to change your loop
try {
while ((rsslink = br.readLine()) != null)
{
}
}
to
try {
StringBuilder sb= new StringBuilder();
while ((rsslink = br.readLine()) != null)
{
sb.append(rsslink);
}
rsslink = sb.toString();
}
Use this:
String rsslink = "";
InputStream is = getResources().openRawResource(R.raw.xmlsource);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
try {
while ((line = br.readLine()) != null)
{
rsslink +=line ;
}
}
catch (IOException e)
{
e.printStackTrace();
}
String RSS_LINK = rsslink;
Log.d(Constants.TAG, "Service started");
List<RssItem> rssItems = null;
try
{
XMLRssParser parser = new XMLRssParser();
rssItems = parser.parse(getInputStream(RSS_LINK));
Better your StringBuffer orStringBuilder.
StringBuilder rsslink = new StringBuilder();
InputStream is = getResources().openRawResource(R.raw.xmlsource);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
try {
while ((line = br.readLine()) != null)
{
rsslink.append(line);
}
}
catch (IOException e)
{
e.printStackTrace();
}
String RSS_LINK = rsslink.toString();