I'm developing a app which opens a file and writes its content in another existing file with adifferent name.
The problem is that some chars, which don't exist in ASCII(I think), for example (char)144 or (char)154, are replaced by (char)63 or the *** question mark ->?.
I have tried to change VM charset but the problem is not solved.
Here the part of the code we are interested in:
File out = new File("new_clientK.swf");
BufferedReader reader = new BufferedReader(new FileReader(new File("input.swf")));
PrintWriter writer = new PrintWriter(new FileWriter(out));
String line = null;
//The first line is edited
line = reader.readLine();
writer.append(line.replace(oldstring, newstring));
writer.append((char) 10);
//The first line is added, now, I get all the remaining code and add it
//char by char
int charnum = 0;
while ((charnum = reader.read()) != -1) {
writer.append((char) (charnum));
}
reader.close();
writer.close();
So you should not use a text oriented API like BufferedReader/PrintWriter but some raw binary API like FileInputStream/FileOutputStream.
Because you can't even play with encoding, a SWF file is not a document and contains raw binary data.
Related
This question already has answers here:
Find a line in a file and remove it
(17 answers)
Removing Nth line of File with BufferedReader/BufferedWriter
(1 answer)
Closed 2 years ago.
I have a text file that will have repeated lines of the following information (without bullet points):
Code: 12345
john.doe#gmail.com
10935710517038750
In each "set", the numbers would be different as well as the email address. This is just an example.
What I want to do is scan through the text file, fine the line with the specific code I am searching for, then delete that code, email, and number line. Like, the line with the code in it as well as the next two lines.
I cannot, for the life of me, figure out how to do this. I learned how to replace these lines with something else, but I would like to erase them completely, preferably without having to make a brand new text file every single time, unless there is a way to make the new text file with the deleted lines, and replace the old file with this new one.
Here is the relevant code I have, in segments. The code replaces all lines matching the oldLine variable with an empty line. That isn't what I want, but I can't figure it out otherwise. I had gotten most of this code from an example elsewhere.
//Instantiating the File class
String filePath = "C:\\\\Users\\\\taylo\\\\Astronomy\\\\Which Bright Stars Are Visible\\\\StoreVerificationCodes.txt";
//Instantiating the Scanner class to read the file
Scanner sc = new Scanner(new File(filePath));
//instantiating the StringBuffer class
StringBuffer buffer = new StringBuffer();
//Reading lines of the file and appending them to StringBuffer
while (sc.hasNextLine()) {
buffer.append(sc.nextLine()+System.lineSeparator());
}
String fileContents = buffer.toString();
System.out.println("Contents of the file: "+fileContents);
//closing the Scanner object
sc.close();
String oldLine = "Code: 12345";
String newLine = "";
//Replacing the old line with new line
fileContents = fileContents.replaceAll(oldLine, newLine);
//instantiating the FileWriter class
FileWriter writer = new FileWriter(filePath);
System.out.println("");
System.out.println("new data: "+fileContents);
writer.append(fileContents);
writer.flush();
writer.close();
Well, I think, what you are looking for is substring method. I believe there would be some reason why you have this requirement where you just have the code and you have to delete the next two lines of that set also. Please have a look at below code. It should work, given that the structure of your file is fixed and not going to change.
String filePath = "C:/Users/taylo/Astronomy/Which Bright Stars Are Visible/StoreVerificationCodes.txt";
//Instantiating the Scanner class to read the file
Scanner sc = new Scanner(new File(filePath));
//instantiating the StringBuffer class
StringBuffer buffer = new StringBuffer();
//Reading lines of the file and appending them to StringBuffer
while (sc.hasNextLine()) {
buffer.append(sc.nextLine()+System.lineSeparator());
}
String fileContents = buffer.toString();
System.out.println("Contents of the file: "+fileContents);
//closing the Scanner object
sc.close();
String oldLine = "Code: 789678";
String newLine = "";
// My changes starts here.............
String codePattern = "Code:"; // A fixed pattern
int firstIndex = fileContents.indexOf(oldLine); // To get the index of code you looking for.
int nextIndex= fileContents.indexOf(codePattern, firstIndex+1);
if(nextIndex != -1) {
nextIndex = fileContents.indexOf(codePattern, firstIndex+1) -5;
fileContents = fileContents.substring(0, firstIndex) + fileContents.substring(nextIndex+3);
}
else
fileContents = fileContents.substring(0, firstIndex);
// My changes done here.............
//fileContents = fileContents.replaceAll(oldLine, newLine); //No need
FileWriter writer = new FileWriter(filePath);
System.out.println("");
System.out.println("new data: "+fileContents);
writer.append(fileContents);
writer.flush();
writer.close();
I'm importing a file into my code and trying to print it. the file contains
i don't like cake.
pizza is good.
i don’t like "cookies" to.
17.
29.
the second dont has a "right single quotation" and when I print it the output is
don�t
the question mark is printed out a blank square. is there a way to convert it to a regular apostrophe?
EDIT:
public class Somethingsomething {
public static void main(String[] args) throws FileNotFoundException,
IOException {
ArrayList<String> list = new ArrayList<String>();
File file = new File("D:\\project1Test.txt");//D:\\project1Test.txt
if(file.exists()){//checks if file exist
FileInputStream fileStream = new FileInputStream(file);
InputStreamReader input = new InputStreamReader(fileStream);
BufferedReader reader = new BufferedReader(input);
String line;
while( (line = reader.readLine()) != null) {
list.add(line);
}
for(int i = 0; i < list.size(); i ++){
System.out.println(list.get(i));
}
}
}}
it should print as normal but the second "don't" has a white block on the apostrophe
this is the file I'm using https://www.mediafire.com/file/8rk7nwilpj7rn7s/project1Test.txt
edit: if it helps even more my the full document where the character is found here
https://www.nytimes.com/2018/03/25/business/economy/labor-professionals.html
It’s all about character encoding. The way characters are represented isn't always the same and they tend to get misinterpreted.
Characters are usually stored as numbers that depend on the encoding standard (and there are so many of them). For example in ASCII, "a" is 97, and in UTF-8 it's 61.
Now when you see funny characters such as the question mark (called replacement character) in this case, it's usually that an encoding standard is being misinterpreted as another standard, and the replacement character is used to replace the unknown or misinterpreted character.
To fix your problem you need to tell your reader to read your file using a specific character encoding, say SOME-CHARSET.
Replace this:
InputStreamReader input = new InputStreamReader(fileStream);
with this:
InputStreamReader input = new InputStreamReader(fileStream, "SOME-CHARSET");
A list of charsets is available here. Unfortunately, you might want to go through them one by one. A short list of most common ones could be found here.
Your problem is almost certainly the encoding scheme you are using. You can read a file in most any encoding scheme you want. Just tell Java how your input was encoded. UTF-8 is common on Linux. Windows native is CP-1250.
This is the sort of problem you have all the time if you are processing files created on a different OS.
See here and Here
I'll give you a different approach...
Use the appropriate means for reading plain text files. Try this:
public static String getTxtContent(String path)
{
try(BufferedReader br = new BufferedReader(new FileReader(path)))
{
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
return sb.toString();
}catch(IOException fex){ return null; }
}
I'm trying to read in a file and modify the text, but I need to keep new lines when doing so. For example, if I were to read in a file that contained:
This is some text.
This is some more text.
It would just read in as
This is some text.This is some more text.
How do I keep that space? I think it has something to do with the /n escape character. I've seen using BufferReader and FileReader, but we haven't learned that in my class yet, so is there another way? What I've tried is something like this:
if (ch == 10)
{
ch = '\n';
fileOut.print(ch);
}
10 is the ASCII table code for a new line, so I thought Java could recognize it as that, but it doesn't.
In Java 8:
You can read lines using:
List<String> yourFileLines = Files.readAllLines(Paths.get("your_file"));
Then collect strings:
String collect = yourFileLines.stream().filter(StringUtils::isNotBlank).collect(Collectors.joining(" "));
The problem is that you (possibly) want to read your file a line at a time, and then you want to write it back a line at a time (keeping empty lines).
The following source does that, it reads the input file one line at a time, and writes it back one line at a time (keeping empty lines).
The only problem is ... it possibly changes the new line, maybe you are reading a unix file and write a dos file or vice-versa depending on the system you are running in and the source type of the file you a reading.
Keeping the original newline can introduce a lot complexity, read BufferedReader and PrintWriter api docs for more information.
public void process(File input , File output){
try(InputStream in = new FileInputStream(input);
OutputStream out = new FileOutputStream(output)){
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"),true);
PrintWriter writer = new PrintWriter( new OutputStreamWriter(out,"utf-8"));
String line=null;
while((line=reader.readLine())!=null){
String processed = proces(line);
writer.println(processed);
}
} catch (IOException e) {
// Some exception management
}
}
public String proces(String line){
return line;
}
/n should be \n
if (ch == 10)
{
ch = '\n';
fileOut.print(ch);
}
Is that a typo?
ch = '/n';
otherwise use
ch = '\n';
I want to edit certain values(a row values) of a csv file based on a specific value of that row (an id). I am able to read and write (append) the values in it but cannot figure out how to edit and delete them.
Here is a small fragment of code for what I am doing for reading the file and appending values:
FileWriter writer = new FileWriter("file.csv", true);
try {
FileInputStream fstream = new FileInputStream("file.csv");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = br.readLine()) != null) {
String[] fields = strLine.split(",");
if (fields[1].equals("value") {
fields[1] = "different value";
}
writer.append(fields);
}
catch(...)
}
But I can't work out how to write the values back into the same spot in the file.
Unfortunately you can't open a single file for both reading and writing at the same time. You need to read the file and close it before opening it for writing.
The potential solutions are:
Write the output to a different file and then replace the original when complete
Keep all the output in internal variables then, once you've finished reading, close the file and reopen it for writing.
hello fellow java developers. I'm having a very strange issue.
I'm trying to read a csv file line by line. Im at the point where Im just testing out the reading of the lines. ONly each time that I read a line, the line contains square characters between each character of text. I even saved the file as a txt file in wordpad and notepad with no change.
Thus I must be doing something stupid...
I have a csv file, standard csv file, yes a text file with commas in it. I try to read a line of text, but the text is all f-ed up and cannot find the phrase within the text.
Any advice? code below.
//open csv
File filReadMe = new File(strRoot + "data2.csv");
BufferedReader brReadMe = new BufferedReader
(new InputStreamReader(new FileInputStream(filReadMe)));
String strLine = brReadMe.readLine();
//for all lines
while (strLine != null){
//if line contains "(see also"
if (strLine.toLowerCase().contains("(see also")){
//write line from "(see also" to ")"
int iBegin = strLine.toLowerCase().indexOf("(see also");
String strTemp = strLine.substring(iBegin);
int iLittleEnd = strTemp.indexOf(")");
System.out.println(strLine.substring(iBegin, iBegin + iLittleEnd));
}
//update line
strLine = brReadMe.readLine();
} //end for
brReadMe.close();
I can only think that this is an inconsistent character encoding. Open the file in notepad, choose Save As, and select UTF-8 in the drop down for "encoding". Then add "UTF-8" as a second parameter to InputStreamReader, e.g.
BufferedReader brReadMe = new BufferedReader
(new InputStreamReader(new FileInputStream(filReadMe), "UTF-8"));
That should sort out any inconsistencies with encoding.