Okay, so what I'm trying to do is create a java program that uses data obtained from a web service. I can get the data, but it's in the format of an XML document, and when I print it to the (Eclipse) console, there are spaces between every letter and the replaceAll method doesn't work. The relevant part of the code is below.
BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(webAdress).openStream()));
String XMLcode = reader.readLine();
XMLcode = XMLcode.concat(reader.readLine());
XMLcode = XMLcode.replaceAll(" ", "");
System.out.println(XMLcode); //in the finished program, I will do something with the data in the XML document.
The results look like this-
þÿ < ? x m l v e r s i o n = " 1 . 0 " e n c o d i n g = " U T F - 8 " ? >
followed by the actual data I'm looking for. Some internet searches implied that the þÿ meant that this was a text-encoding problem, but all methods I could find for converting UTF-8 into UTF-16 did not help (they do, however, change the þÿ into ??). Does anybody have any idea how to fix this, or know of a "standard" way to read XML that does not require it available in a file?
NOTE- I did not make the web service in question, and as such cannot modify it and don't really know how it works.
Maybe is a good idea try with:
new BufferedReader(new InputStreamReader(new URL(webAdress).openStream(), "UTF-16"));
you can use the following code to test it:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
public class CharsetChanging {
public static void main(final String[] args) throws IOException {
File infile = new File("/tmp/utf16.txt");
FileInputStream inputStream = new FileInputStream(infile);
Reader in = new InputStreamReader(inputStream, "UTF-16");
int read;
while ((read = in.read()) != -1) {
System.out.print(Character.toChars(read));
}
in.close();
}
}
just replace new FileInputStream(infile) with new URL(webAdress).openStream()
why dont you try
XMLcode = XMLcode.replaceAll("\s","")
Related
I'm a beginner in java programming and i'm trying to create a hex viewer in java, my IDE is Netbeans. Below is the code.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import static java.lang.System.out;
import javax.swing.JFileChooser;
public class hope {
public static void main(String[] args) throws IOException {
JFileChooser open = new JFileChooser();
open.showOpenDialog(null);
File f = open.getSelectedFile();
InputStream is = new FileInputStream(f);
int bytesCounter = 0;
int value = 0;
StringBuilder sbHex = new StringBuilder();
StringBuilder sbResult = new StringBuilder();
while ((value = is.read()) != -1) {
//convert to hex value with "X" formatter
sbHex.append(String.format("%02X ", value));
//if 16 bytes are read, reset the counter,
//clear the StringBuilder for formatting purpose only.
if (bytesCounter == 15) {
sbResult.append(sbHex).append("\n");
sbHex.setLength(0);
bytesCounter = 0;
} else {
bytesCounter++;
}
}
//if still got content
if (bytesCounter != 0) {
//add spaces more formatting purpose only
for (; bytesCounter < 16; bytesCounter++) {
//1 character 3 spaces
sbHex.append(" ");
}
sbResult.append(sbHex).append("\n");
}
out.print(sbResult);
is.close();
}
}
The problem are:
1. It doesn't read the files fast enough"It takes a minute to read a file of 200kb"
2. It gives "Out of Memory" error when I tried a large file e.g. 80mb
What I want it to do:
1. Display all the hex code in seconds "Read and display hex of any size of file"
2. read file of any size without error code.
The Question:
What do I need to change or add in my code to achieve the above "What I want it to do"?
For this simple example, the key is to use "Buffered" input stream.
Change this line of code:
InputStream is = new FileInputStream(f);
to:
InputStream is = new BufferedInputStream( new FileInputStream(f));
You will get a much better result.
(But to fix the Out of Memory error, you have to think about a different approach since currently you are "caching" all the data to one string which will eat all your memory. Maybe print/clear the string builder each time the counter reaches 15 or higher? You can try and let us know. :)
I have file in my computer which have .file extension , I want to read it 9 character by 9 character. I know that I can read file by this code, but what should I do when my file is not .txt?does java support to read .file s with this code?
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
is = new FileInputStream("c:/test.txt");
// create new input stream reader
isr = new InputStreamReader(is);
// create new buffered reader
br = new BufferedReader(isr);
// creates buffer
char[] cbuf = new char[is.available()];
for (int i = 0; i < 90000000; i += 9) {
// reads characters to buffer, offset i, len 9
br.read(cbuf, i, 9);}
The extension of a file is totally irrelevant. Extensions like .txt are mere conventions to help your operating system choose the right program when you open it.
So you can store text in any file (.txt, .file, .foobar if you are so inclined...), provided you know what kind of data it contains, and read it accordingly from your program.
So yes, Java can read .file files, and your code will work fine if that file contains text.
does java support to read .file s with this code?
No, since c:/test.txt is hard coded. If it wouldn't yes it would support it.
Yes it's possible if you write is = new FileInputStream("c:/test.file");
Yes, it reads any file you give it the same way. You can pass any file path with any extension to the FileInputStream constructor.
Anyone can read any file you want, since a file is just a sequence of bytes. The extension tells you in what format the bytes should be read, so when we have a .txt file we know that this is a file with sequences of characters.
When you have a file format called .file we know that it should be (according to you) a 9x9 set of characters. This way we know what to read and do that.
Since the .file format is characters I would say yes, you can read that with your code for instance with this:
public String[] readFileFormat (final File file) throws IOException {
if (file.exists()) {
final String[] lines = new String[9];
final BufferedReader reader = new BufferedReader ( new FileReader( file ) );
for ( int i = 0; i < lines.length; i++ ) {
lines[i] = reader.readLine();
if (lines[i] == null || lines[i].isEmpty() || lines[i].length() < 9)
throw new RuntimeException ("Line is empty when it should be filled!");
else if (lines[i].length() > 9)
throw new RuntimeException ("Line does not have exactly 9 characters!");
}
reader.close();
return lines;
}
return null;
}
The extension is totally irrelevant, so it can be .file, .txt or whatever you want it to be.
Here is an example of reading in a file with BuffereInputStream that reads a file of type .file. This is part of a larger guide that discusses 15 ways to read files in Java.
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class ReadFile_BufferedInputStream_Read {
public static void main(String [] pArgs) throws FileNotFoundException, IOException {
String fileName = "c:\\temp\\sample-10KB.file";
File file = new File(fileName);
FileInputStream fileInputStream = new FileInputStream(file);
try (BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream)) {
int singleCharInt;
char singleChar;
while((singleCharInt = bufferedInputStream.read()) != -1) {
singleChar = (char) singleCharInt;
System.out.print(singleChar);
}
}
}
}
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.IOException;
public class TextFile {
private static void doReadWriteTextFile() {
try {
// input/output file names
String inputFileName = "README_InputFile.rtf";
// Create FileReader Object
FileReader inputFileReader = new FileReader(inputFileName);
// Create Buffered/PrintWriter Objects
BufferedReader inputStream = new BufferedReader(inputFileReader);
while ((inLine = inputStream.readLine()) != null) {
System.out.println(inLine);
}
inputStream.close();
} catch (IOException e) {
System.out.println("IOException:");
e.printStackTrace();
}
}
public static void main(String[] args) {
doReadTextFile();
}
}
I'm just learning Java, so take it easy on me. My program's objective is to read a text file and output it into another text file in reverse order. The problem is the professor taught us to to deal with strings and reverse it and such, but nothing about importing/exporting files. Instead, he gave us the following sample code which should import a file. The file returns 3 errors: The first two deal with inLine not being a symbol on lines 24 and 25. The last cannot find the symbol doReadTextFile on line 40.
I have no idea how to read this file and make the necessary changes to reverse and output into a new file. Any help is hugely appreciated.
I also had to change the file type from .txt to .rtf. I'm not sure if that affects how I need to go about this.
EDIT I defined inLine and fixed the doReadWritetextFile naming error, which fixed all my compiling errors. Any help on outputting into new file still appreciated!
I'm also aware he gave me bad sample code. It's supposed to be so we can learn troubleshooting, but with no working code to go off of and very extremely knowledge of the language, it's very difficult to see what's wrong. Thanks for the help!
The good practice will be to use a BufferedFileReader
BufferedFileReader bf = new BufferedFileReader(new FileReader(new File("your_file.your_extention")));
Then you can read lines in your file :
// Initilisation of the inLine variable...
String inLine = null;
while((inLine = bf.readLine()) != null){
System.out.println(inLine);
}
To output a file, you can use StringBuilder to hold the file contents:
private static void doReadWriteTextFile()
{
....
StringBuilder sb = new StringBuilder();
while ((inLine = inputStream.readLine()) != null)
{
sb.append(inline);
}
FileWriter writer = new FileWriter(new File("C:\\temp\\test.txt"));
BufferedWriter bw = new BufferedWriter(writer);
w.write(sb.toString());
bw.close();
}
I have a slight problem trying to save a file in java.
For some reason the content I get after saving my file is different from what I have when I read it.
I guess this is related to file encoding, but without being sure.
Here is test code I put together. The idea is basically to read a file, and save it again.
When I open both files, they are different.
package workspaceFun;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.commons.codec.DecoderException;
public class FileSaveTest {
public static void main(String[] args) throws IOException, DecoderException{
String location = "test.location";
File locationFile = new File(location);
FileInputStream fis = new FileInputStream(locationFile);
InputStreamReader r = new InputStreamReader(fis, Charset.forName("UTF-8"));
System.out.println(r.getEncoding());
StringBuilder builder = new StringBuilder();
int ch;
while((ch = fis.read()) != -1){
builder.append((char)ch);
}
String fullLocationString = builder.toString();
//Now we want to save back
FileOutputStream fos = new FileOutputStream("C:/Users/me/Desktop/test");
byte[] b = fullLocationString.getBytes();
fos.write(b);
fos.close();
r.close();
}
}
An extract from the input file (opened as plain text using Sublime 2):
40b1 8b81 23bc 0014 1a25 96e7 a393 be1e
and from the output file :
40c2 b1c2 8bc2 8123 c2bc 0014 1a25 c296
The getEncoding method returns "UTF8". Trying to save the output file using the same charset doest not seem to solve the issue.
What puzzles me is that when I try to read the input file using Hex from apache.commons.codec like this :
String hexLocationString2 = Hex.encodeHexString(fullLocationString.getBytes("UTF-8"));
The String already looks like my output file, not the input.
Would you have any idea on what can go wrong?
Thanks
Extra info for those being interested, I am trying to read an eclipse .location file.
EDIT: I placed the file online so that you can test the code
I believe is the way you are reading the stream.
You are using FileInputStream directly to read the content instead of wrapping it in the InputStreamReader
By using the InputStreamReader you may determine which Charset to use.
Take in consideration that the Charset defined in the InputStream must be the same you expect as InputStream doesn't detect charsets, it just reads them in that specific format.
Try the following changes:
InputStreamReader r = new InputStreamReader(new FileInputStream(locationFile), StandardCharsets.UTF_8);
then instead of fos.read() use r.read()
Finally when writing the String get the bytes in the same Charset as your Reader
FileOutputStream fos = new FileOutputStream("C:/Users/me/Desktop/test");
fos.write(fullLocationString.getBytes(StandardCharsets.UTF_8));
fos.close()
Try to read and write back as below:
public class FileSaveTest {
public static void main(String[] args) throws IOException {
String location = "D:\\test.txt";
BufferedReader br = new BufferedReader(new FileReader(location));
StringBuilder sb = new StringBuilder();
try {
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
if (line != null)
sb.append(System.lineSeparator());
}
} finally {
br.close();
}
FileOutputStream fos = new FileOutputStream("D:\\text_created.txt");
byte[] b = sb.toString().getBytes();
fos.write(b);
fos.close();
}
}
Test file contains both Cirillic and Latin characters.
SDFASDF
XXFsd1
12312
іва
I wrote the below part of the code but I couldn't bind the arraylist with search and replace
so my csv file is as like below
1/1/1;7/6/1
1/1/2;7/7/1
I want to search the file 1.cfg for 1/1/1 and change it to 7/6/1 and 1/1/2 change to 7/7/1 and it goes so on.
Thank you all in advance
It's now only printing in a new file only the last line of the old File
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class ChangeConfiguration {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args)
{
try{
// Open the file that is the first
// command line parameter
FileInputStream degistirilecek = new FileInputStream("c:/Config_Changer.csv");
FileInputStream config = new FileInputStream("c:/1.cfg");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(config);
DataInputStream degistir = new DataInputStream(degistirilecek);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
BufferedReader brdegis = new BufferedReader(new InputStreamReader(degistir));
List<Object> arrayLines = new ArrayList<Object>();
Object contents;
while ((contents = brdegis.readLine()) != null)
{
arrayLines.add(contents);
}
System.out.println(arrayLines + "\n");
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
//Couldn't modify this part error is here :(
BufferedWriter out = new BufferedWriter(new FileWriter("c:/1_new.cfg"));
out.write(strLine);
out.close();
}
in.close();
degistir.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
You are opening the file for reading when you declare:
BufferedReader br = new BufferedReader(new InputStreamReader(in));
If you know the entire file will fit in memory, I recommend doing the following :
Open the file and read it's contents in memory into a giant string, then close the file.
Apply your replace in one shot to the giant string.
Open the file and write (e.g use a BufferedWriter) out the contents of the giant string, then close the file.
As a side note, your code as posted will not compile. The quality of the responses you receive are correlated with the quality of the question asked. Always include an SCCE with your question to increase the chance of getting a precise answer to your question.
can you elaborate the purpose of the program?
if it is a simple content replacement in a file.
then just read a line and store it in a string. then use string replace method for replacing a text in a string.
eg:
newStrog=oldString.replace(oldVlue,newValue);