String index out of range: -1 working with XML file - java

I downloaded an xml file from web service. If I open file from file system is formed correctly, but when I run my code isn't formed correctly.
A part of xml file formed correctly, it opened from file system:
<?xml version="1.0" encoding="UTF-8"?><ns3:FatturaElettronica xmlns:ns3="http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2" xmlns:ns2="http://www.w3.org/2000/09/xmldsig#" versione="FPR12">
Here the same xml file managed by my code:
ÿþ<
I can't copy the code and I put an image of what I see on the eclipse console.
I tryed different ways to manage this file, but nothing worked.
This is the code that it manages files. I put all ways I tryed to solve the error.
private static String readFile(File file, Writer writerArg) throws FileNotFoundException, IOException,Exception
{
FileInputStream fis = null;
InputStreamReader isr = null;
String typeEncoding = null;
/*
* First way
*
* BufferedReader br = new BufferedReader(new FileReader(fileName));
String nextLine = "";
StringBuffer sb = new StringBuffer();
while ((nextLine = br.readLine()) != null)
{
// System.out.println("Writing: " + nextLine);
writerArg.write(nextLine);
// sb.append(nextLine);
sb.append(nextLine+"\n");
} // Convert the content into to a string
String clobData = sb.toString().trim();
*/
/*
* Second way
*
* fis = new FileInputStream(file);
isr = new InputStreamReader(fis);
typeEncoding = isr.getEncoding();
Charset inputCharset = Charset.forName(typeEncoding);
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), inputCharset));
String str;
String nextLine = "";
StringBuffer sb = new StringBuffer();
while ((nextLine = in.readLine()) != null) {
System.out.println(nextLine);
writerArg.write(nextLine);
// sb.append(nextLine);
sb.append(nextLine+"\n");
}
String clobData = sb.toString().trim();
// Return the data.
return clobData;
*/
/* Third way */
String data = "";
data = new String(Files.readAllBytes(Paths.get(file.getAbsolutePath())));
System.out.println(data);
return data;
}
And when the below code receives the string I get the error: "String index out of range: -1"
schema=stringXml.substring(0,stringXml.indexOf("<FatturaElettronicaHeader")).trim();
The first way downloaded thousands of files and managed them. Only this file gives my this error. It's from yesterday that I'm looking for a way to solve the error.
Can anyone give my any idea?

Related

How to replace both int and string

I have a String like "HelloWorld!9090Hello" in a file, and i want to replace the whole string with a new One, Tried this but didn't helped
Example File abc.txt:
a=HelloWorld!9090Hello
String neww = "abcdef";
File file = new File("abc.txt");
File wr = new File("tmp.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
// tried even line.toString();//
String rline= line.replace("HelloWorld!9090Hello", neww);
BufferWrite(rline,wr);
}
br.close();
public static void BufferWrite(String St,File file) throws IOException{
FileWriter fw = new FileWriter(file.getAbsoluteFile(),true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(St);
bw.write("\r\n");
bw.close();
}
The BufferWrite() writes text to the tmp.txt file..
Result :
a=HelloWorld!9090Hello
I ran your exact code in Eclipse, and it creates the tmp file correctly for me and it has "abcdef" in it.
Did you make sure you actually started with exactly "HelloWorld!9090Hello" in your input file? It looks like you are starting with "a=HelloWorld!9090Hello", not "HelloWorld!9090Hello". The replace function will only work when the Strings are an exact match. If you're starting with "a=HelloWorld!9090Hello", change the replace function to the following:
String rline= line.replace("a=HelloWorld!9090Hello", neww);

File Reader Method

So I wrote this file reader method that should return a string of everything that is in the file, but it isn't working properly. Writing into the file works perfectly, but this reading method doesn't. What the method does currently is it reads the last string/text added, but it does not read the file from start to finish. 'br' is my bufferedReader, which is declared somewhere else in the same class.
Here's how br is defined:
private static FileInputStream fis;
private static BufferedReader br;
and then in the constructor:
fis = new FileInputStream(file);
br = new BufferedReader(new InputStreamReader(fis));
Here's the method:
public String readStuff(){
String line = "";
String r = "";
try{
while((line = br.readLine()) != null){
System.out.println(line + " read ");
r+= line;
}
//br.close(); JDK 7 does this automatically apparently
}catch(IOException e){
e.printStackTrace();
System.out.println("Error at readStuff!");
}
return r;
I know I'm making either a logic mistake or some obvious error, I just don't know where.
If you want to read the entire file twice, you will have to close it and open new streams/readers next time.
Those streams/readers should be local to the method, not members, and certainly not static.
Using File and FileReader You can Read / Write File From Dir.
you can get File using File class object
File file = new File("file.txt");
and After Process to read that file
FileReader fr = new FileReader(file);
There are Whole Code to read File...
File file = new File("G:\\Neon\\data.txt");
FileReader fr = new FileReader(file);
String data = "";
while((i = fr.read()) != -1)
{
data = data + (char)i;
}
System.out.println(data);

read from file and write some parts in another file

I have to read from a text file and format the input. I'm new to java reading from files, and I don't know how to work with just some parts of what I read
Here is the initial file: http://pastebin.com/D0paWtAd
And I have to write in another file the following output:
Average,Joe,44,31,18,12,9,10
I've managed just to take everything from the file and print it to output. I would need help just in taking the output I need and print it to the screen. Any help is appreciated.
This is what I wrote up to now:
public class FileParsing {
public static String
read(String filename) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("C:\\Users\\Bogdi\\Desktop\\example.txt"));
String s;
StringBuilder sb = new StringBuilder();
while((s = in.readLine())!= null) sb.append(s + "\n");
in.close();
return sb.toString();
}
If your goal is to do the specified output in another file you don't need to first get the content of your file in a StringBuilder before processing it, you can append the processed datas directly in a StringBuilder then you can write the result in a file. Here is an example that would work for the given file but you may have to modify it if the keys change in the future:
The following method will correctly process the datas from your file
public static String read(String filename) throws IOException {
BufferedReader in = new BufferedReader(new FileReader(filename));
String s;
StringBuilder sb = new StringBuilder();
while((s = in.readLine())!= null) {
String[] split1 = s.split("=");
if (split1[0].equals("name")) {
StringTokenizer tokenizer = new StringTokenizer(split1[1]);
sb.append(tokenizer.nextToken());
sb.append(",");
sb.append(tokenizer.nextToken());
sb.append(",");
} else if (split1[0].equals("index")) {
sb.append(split1[1] + ",");
} else if (split1[0].equals("FBid")) {
sb.append(split1[1]);
} else {
StringTokenizer tokenizer = new StringTokenizer(split1[1]);
String wasted = tokenizer.nextToken();
sb.append(tokenizer.nextToken() + ",");
}
}
in.close();
return sb.toString();
}
The next method will read any string to a file
public static void writeStringToFile(String string, String filePath) throws IOException {
BufferedWriter writer = new BufferedWriter(
new FileWriter(
new File(filePath)
)
);
writer.write(string);
writer.newLine();
writer.flush();
writer.close();
}
And here is a simple tests (File1.txt contains the datas from the file you shared on paste bin and I write them in another file)
public static void main(String[] args) throws Exception {
String datas = read("C:\\Tests\\File1.txt");
System.out.println(datas);
writeStringToFile(datas, "C:\\Tests\\FileOuput.txt" );
}
It will produce the exact output that you are expecting
[EDIT] #idk, apparently you have an exception executing my example, while it is working fine for me. That could only mean there is an error at data level. Here is the data sample that I used (and I believe I exactly copy the datas you shared)
And here is the result:
Good to know you are using "StringBuilder" component instead being concatenating your String values, way to go :).
More than knowledge on the Java.IO API to work with files, you will need some logic to get the results you expect. Here I came with an approach that could help you, not perfect, but can point you on how to face this problem.
//Reference to your file
String myFilePath = "c:/dev/myFile.txt";
File myFile = new File(myFilePath);
//Create a buffered reader, which is a good start
BufferedReader breader = new BufferedReader(new FileReader(myFile));
//Define this variable called line that will evaluate each line of our file
String line = null;
//I will use a StringBuilder to append the information I need
StringBuilder appender = new StringBuilder();
while ((line = breader.readLine()) != null) {
//First, I will obtain the characters after "equals" sign
String afterEquals = line.substring(line.indexOf("=") + 1, line.length());
//Then, if it contains digits...
if (afterEquals.matches(".*\\d+.*")) {
//I will just get the digits from the line
afterEquals = afterEquals.replaceAll("\\D+","");
}
//Finally, append the contents
appender.append(afterEquals);
appender.append(",");//This is the comma you want to include
}
//I will delete the last comma
appender.deleteCharAt(appender.length() - 1);
//Close the reader...
breader.close();
//Then create a process to write the content
BufferedWriter myWriter = new BufferedWriter(new FileWriter(new File("myResultFile.txt")));
//Write the full contents I get from my appender :)
myWriter.write(appender.toString());
//Close the writer
myWriter.close();
}
Hope this can help you. Happy coding!

Get .txt file and parse it by new line or comma

I have a .txt file in this format:
file.txt (each line has text)
text1
text2
longtext3
...
..
I am downloding it:
URL url = new URL(FILE_URL);
URLConnection connection = url.openConnection();
connection.connect();
// download the file
InputStream input = newBufferedInputStream(connection.getInputStream());
How can I parse this input so I get the text in each new line?
I tried something like that:
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
LIST.add(line);
} }
but I don't want to save it,so I don't have the File instance
I can save in this format:
text1,text2,longtext3,....
If its more simple to extract it
You can use an InputStreamReader (http://docs.oracle.com/javase/7/docs/api/java/io/InputStreamReader.html).
Put it between your InputStream and your BufferedReader. Now you don't need the File instance (and so there is no need to save it first).
Something like ...
InputStream input = new BufferedInputStream(connection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = br.readLine()) != null) {
LIST.add(line);
// further break the line into a list of comma separated values
List<String> commaSeparatedValues = Arrays.asList(line.split(","));
}
...
You can use the Scanner class
String result = "";
Scanner in = new Scanner(new FileInputStream(file));
while(in.hasNextLine())
result += in.nextLine() + ",";
this will create a string like this:
text1,text2,longtext3,....
I'm not sure what you're asking but I think you want to save each line of a text file. This worked for me, it puts every line into one long string.
public static void main( String[] args )
{
String FILE_URL = "http://www.google.com/robots.txt";
String FILE_CONTENTS = "";
try
{
URL url = new URL(FILE_URL);
URLConnection connection = url.openConnection();
connection.connect();
// download the file
BufferedInputStream input = new BufferedInputStream(connection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line = reader.readLine();
while( line != null )
{
FILE_CONTENTS += line;
line = reader.readLine();
}
}
catch( MalformedURLException e )
{
System.out.println("Malformed URL" );
}
catch( IOException e )
{
System.out.println( "IOException" );
}
}
Try to scan as normal text and replace every '\n' in a comma...

Reading CSVs from a zip file a line at a time

I've got a Spring MVC app with a file upload capability. Files are passed to the controller as MultipartFile from which it's easy to get an InputStream. I'm uploading zip files that contain CSVs and I'm struggling to find a way to open the CSVs and read them a line at a time. There are plenty of examples on the 'net of reading into a fixed sizes buffer. I've tried this, but the buffers don't concatenate very well and it soon gets out of sync and uses a lot of memory:
ZipEntry entry = input.getNextEntry();
while(entry != null)
{
if (entry.getName().matches("Data/CSV/[a-z]{0,1}[a-z]{0,1}.csv"))
{
final String fullPath = entry.getName();
final String filename = fullPath.substring(fullPath.lastIndexOf('/') + 1);
visitor.startFile(filename);
final StringBuilder fileContent = new StringBuilder();
final byte[] buffer = new byte[1024];
while (input.read(buffer) > 0)
fileContent.append(new String(buffer));
final String[] lines = fileContent.toString().split("\n");
for(String line : lines)
{
final String[] columns = line.split(",");
final String postcode = columns[0].replace(" ", "").replace("\"", "");
if (columns.length > 3)
visitor.location(postcode, "", "");
}
visitor.endFile();
}
entry = input.getNextEntry();
}
There must be a better way that actually works.
Not clear if this suits your need, but have you tried opencsv (http://opencsv.sourceforge.net)? Their example is really intuitive:
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
System.out.println(nextLine[0] + nextLine[1] + "etc...");
}
For your case, all you will need is to wrap the zipped file stream into a buffered reader and pass the reader to create a CSVReader and use it:
FileInputStream fis = new FileInputStream(file);
GZIPInputStream gis = new GZIPInputStream(fis);
InputStreamReader isr = new InputStreamReader(gis);
BufferedReader br = new BufferedReader(isr);
CSVReader reader = new CSVReader(br);
You could use a BufferedReader which includes the convenient readLine() method and wont load the entire contents of the file into memory e.g.
BufferedReader in = new BufferedReader(new InputStreamReader(input), 1024);
String line=null;
while((line=br.readLine())!=null) {
String[] columns = line.split(",");
//rest of your code
}

Categories

Resources