Weird character at the beginning of the file? - java

When reading from a file, the first line that I read has a weird character (using BufferedReader). How do I delete this character? I know I can do it manually, but I want to do it the right way.
Picture(NetBeans output)

Using the relevant code from the link that the OP provided, here is an answer to the question which works as intended.
import java.io.*;
public class UTF8ToAnsiUtils {
// FEFF because this is the Unicode char represented by the UTF-8 byte order mark (EF BB BF).
public static final String UTF8_BOM = "\uFEFF";
public static void main(String args[]) {
try {
if (args.length != 2) {
System.out
.println("Usage : java UTF8ToAnsiUtils utf8file ansifile");
System.exit(1);
}
boolean firstLine = true;
FileInputStream fis = new FileInputStream(args[0]);
BufferedReader r = new BufferedReader(new InputStreamReader(fis,
"UTF8"));
FileOutputStream fos = new FileOutputStream(args[1]);
Writer w = new BufferedWriter(new OutputStreamWriter(fos, "Cp1252"));
for (String s = ""; (s = r.readLine()) != null;) {
if (firstLine) {
s = UTF8ToAnsiUtils.removeUTF8BOM(s);
firstLine = false;
}
w.write(s + System.getProperty("line.separator"));
w.flush();
}
w.close();
r.close();
System.exit(0);
}
catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
private static String removeUTF8BOM(String s) {
if (s.startsWith(UTF8_BOM)) {
s = s.substring(1);
}
return s;
}
}

Related

How to read line by line from a file in Android Studio using InputStreamReader

I am able to read in a file right now, but I am confused on how to read then the strings line by line to run through a parser I created. Any suggestions would be helpful.
public void ReadBtn() {
char[] inputBuffer = new char[READ_BLOCK_SIZE];
int charRead;
String s = "";
int READ_BLOCK_SIZE = 100;
//reading text from file
try {
FileInputStream fileIn = openFileInput("mytextfile.txt");
InputStreamReader InputRead = new InputStreamReader(fileIn);
BufferedReader BR = new BufferedReader(InputRead);
while((charRead = InputRead.read(inputBuffer)) > 0) {
// char to string conversion
String readstring = String.copyValueOf(inputBuffer, 0, charRead);
s += readstring;
getContactInfo(s);
}
InputRead.close();
} catch(Exception e) {
e.printStackTrace();
}
}
-Try this code. Replace sdCard path to your file path where mytextfile.txt exists.
String sdCard = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "mytextfile.txt";
String path = sdCard + "/" + MarketPath + "/";
File directory = new File(path);
if (directory.exists()) {
File file = new File(path + fileName);
if (file.exists()) {
String myData = ""; // this variable will store your file text
try {
FileInputStream fis = new FileInputStream(file);
DataInputStream in = new DataInputStream(fis);
BufferedReader br =new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
myData = myData + strLine;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
You can read all lines in an ArrayList:
public void ReadBtn() {
int READ_BLOCK_SIZE = 100;
ArrayList<String> linesList = new ArrayList<>();
// reading text from file
try {
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
BufferedReader br = new BufferedReader(InputRead);
String line = br.readLine();
while (line != null) {
linesList.add(line);
line = br.readLine();
}
InputRead.close();
// here linesList contains an array of strings
for (String s: linesList) {
// do something for each line
}
} catch (Exception e) {
e.printStackTrace();
}
}

How to extract starting of a String in Java

I have a text file with more than 20,000 lines and i need to extract specific line from it. The output of this program is completely blank file.
There are 20,000 lines in the txt file and this ISDN line keeps on repeating lots of time each with different value. My text file contains following data.
RecordType=0(MOC)
sequenceNumber=456456456
callingIMSI=73454353911
callingIMEI=85346344
callingNumber
AddInd=H45345'1
NumPlan=H34634'2
ISDN=94634564366 // Need to extract this "ISDN" line only
public String readTextFile(String fileName) {
String returnValue = "";
FileReader file = null;
String line = "";
String line2 = "";
try {
file = new FileReader(fileName);
BufferedReader reader = new BufferedReader(file);
while ((line = reader.readLine()) != null) {
// extract logic starts here
if (line.startsWith("ISDN") == true) {
System.out.println("hello");
returnValue += line + "\n";
}
}
} catch (FileNotFoundException e) {
throw new RuntimeException("File not found");
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return returnValue;
}
We will assume that you use Java 7, since this is 2014.
Here is a method which will return a List<String> where each element is an ISDN:
private static final Pattern ISDN = Pattern.compile("ISDN=(.*)");
// ...
public List<String> getISDNsFromFile(final String fileName)
throws IOException
{
final Path path = Paths.get(fileName);
final List<String> ret = new ArrayList<>();
Matcher m;
String line;
try (
final BufferedReader reader
= Files.newBufferedReader(path, StandardCharsets.UTF_8);
) {
while ((line = reader.readLine()) != null) {
m = ISDN.matcher(line);
if (m.matches())
ret.add(m.group(1));
}
}
return ret;
}

How to print lines from a file that contain a specific word using java?

How to print lines from a file that contain a specific word using java ?
Want to create a simple utility that allows to find a word in a file and prints the complete line in which given word is present.
I have done this much to count the occurence but don't knoe hoe to print the line containing it...
import java.io.*;
public class SearchThe {
public static void main(String args[])
{
try
{
String stringSearch = "System";
BufferedReader bf = new BufferedReader(new FileReader("d:/sh/test.txt"));
int linecount = 0;
String line;
System.out.println("Searching for " + stringSearch + " in file...");
while (( line = bf.readLine()) != null)
{
linecount++;
int indexfound = line.indexOf(stringSearch);
if (indexfound > -1)
{
System.out.println("Word is at position " + indexfound + " on line " + linecount);
}
}
bf.close();
}
catch (IOException e)
{
System.out.println("IO Error Occurred: " + e.toString());
}
}
}
Suppose you are reading from a file named file1.txt Then you can use the following code to print all the lines which contains a specific word. And lets say you are searching for the word "foo".
import java.util.*;
import java.io.*;
public class Classname
{
public static void main(String args[])
{
File file =new File("file1.txt");
Scanner in = null;
try {
in = new Scanner(file);
while(in.hasNext())
{
String line=in.nextLine();
if(line.contains("foo"))
System.out.println(line);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
Hope this code helps.
public static void grep(Reader inReader, String searchFor) throws IOException {
BufferedReader reader = null;
try {
reader = new BufferedReader(inReader);
String line;
while ((line = reader.readLine()) != null) {
if (line.contains(searchFor)) {
System.out.println(line);
}
}
} finally {
if (reader != null) {
reader.close();
}
}
}
Usage:
grep(new FileReader("file.txt"), "GrepMe");
Have a look at BufferedReader or Scanner for reading the file.
To check if a String contains a word use contains from the String-class.
If you show some effort I'm willing to help you out more.
you'll need to do something like this
public void readfile(){
try {
BufferedReader br;
String line;
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream("file path"), "UTF-8");
br = new BufferedReader(inputStreamReader);
while ((line = br.readLine()) != null) {
if (line.contains("the thing I'm looking for")) {
//do something
}
//or do this
if(line.matches("some regular expression")){
//do something
}
}
// Done with the file
br.close();
br = null;
}
catch (Exception ex) {
ex.printStackTrace();
}
}

delete text file java doesn't work

Here's example:
public static void main (String[] args){
String path = "C:\\Users\\Charbel\\Desktop\\Dictionary.txt";
String temppath = "C:\\Users\\Charbel\\Desktop\\temp.txt";
File file = new File(path);
File tempfile = new File(temppath);
int numl = search("x");
int countL = 0;
String line;
try {
BufferedReader bf = new BufferedReader(new FileReader(path));
BufferedWriter bw = new BufferedWriter(new FileWriter(temppath));
while (( line = bf.readLine()) != null)
{
if(countL != numl){
bw.write(line);
bw.newLine();
}
countL++;
}
bf.close();
bw.close();
file.delete();
boolean successful = tempfile.renameTo(file);
System.out.println(successful);
}
catch (IOException e) {
System.out.println("IO Error Occurred: " + e.toString());
}
}
public static int search(String name)
{
String path = "C:\\Users\\Charbel\\Desktop\\Dictionary.txt";
int countL = 0;
String line;
try {
BufferedReader bf = new BufferedReader(new FileReader(path));
while (( line = bf.readLine()) != null)
{
int indexfound = line.indexOf(name);
if (indexfound == 0) {
return countL;
}
countL++;
}
bf.close();
}
catch (IOException e) {
System.out.println("IO Error Occurred: " + e.toString());
}
return -1;
}
}
Hello there .. i am trying to read the line of a specific string in a text file , get the number of its line , then copy all the data in the file to another text file except the line of the string
the code is sometimes working 100% and sometimes no ; I go to my desktop I see both files the temp and the original one without deleting and renaming it
i think i have a problem in deleting the file what do you think coders ?
Because when the search method find name(actually "x"),don't reach the line bf.close(), so bf is still opened and file.delete() fails.
So, you need to modify the search method to the below:
public static int search(String name) {
String path = "C:\\Users\\Charbel\\Desktop\\Dictionary.txt";
int countL = 0;
String line;
BufferedReader bf = null;
try {
bf = new BufferedReader(new FileReader(path));
while (( line = bf.readLine()) != null)
{
int indexfound = line.indexOf(name);
if (indexfound == 0) {
return countL;
}
countL++;
}
}
catch (IOException e) {
System.out.println("IO Error Occurred: " + e.toString());
}
finally {
if(bf != null) {
try {
bf.close();
}
catch(IOException ignored) {}
}
}
return -1;
}

How to create an file and copy the content from another file into the created file in java? [duplicate]

This question already has answers here:
Standard concise way to copy a file in Java?
(16 answers)
Closed 8 years ago.
I am trying to read a file and write to another file it is not working I invoke the method from the main
public boolean copy(String inputPlayList, String outputPlayList, int numberOfMunites)
{
String start1 = "#EXTINF:";
String afterNum = ";";
try
{
declaring those variable that I would use to pass the method
File fInput, fOutput;
String s;
String a;
assigning those variable to the method
fInput = new File(inputPlayList);
fOutput = new File(outputPlayList);
// Now I am using bufferedRead and BufferedWriter to read and write in a file
BufferedReader br = new BufferedReader(new FileReader(new File(inputPlayList)));
BufferedWriter out = new BufferedWriter(new BufferedWriter(new FileWriter(outputPlayList)));
// creating a while saying while the line is not finish contunue to read
while((s = br.readLine())!= null)
{
if(s.contains(start1)) {
String numberInString = s.substring(start1.length(), s.indexOf(afterNum));
numberOfMunites+= Integer.getInteger(numberInString);
}
// when it is finsh close the file.
out.write(s);
}
out.close();
System.out.println("donne");
}catch ( IOException e)
{
System.err.println("the is an erro that need to be fixed"+e);
}
return false;
}
}
Simplest way in java:
File input = new File("input/file");
File output = new File("output/file");
InputStream is = new FileInputStream(input); // can be any input stream, even url.open()
OutputStream os = new FileOutputStream(output);
byte[] buffer = new byte[4096];//
int read = 0;
while ((read = is.read(buffer)) != -1) {
os.write(buffer, 0, read);
}
is.close();
os.close();
Try Apache Commons IO Utils.
FileUtils.copyFile(new File(inputPlayList),new File(outputPlayList));
Here it is, but I don't understand the meaning of the numberOfminutes argument, what is it for? I've changed implementation to return calculated number of minutes from the function.
import java.io.*;
public class Main {
public static void main(String[] args) {
System.out.println(copy("D:\\1.txt", "D:\\2.txt", 0)); //returns the calculated number of minutes
}
public static int copy(String inputPlayList, String outputPlayList, int numberOfMinutes) {
String start1 = "#EXTINF:";
String afterNum = ";";
try {
BufferedReader br = new BufferedReader(new FileReader(new File(inputPlayList)));
PrintWriter out = new PrintWriter(new FileWriter(outputPlayList));
String s;
while ((s = br.readLine()) != null) {
if (s.contains(start1)) {
String numberInString = s.substring(start1.length(), s.indexOf(afterNum));
numberOfMinutes += Integer.parseInt(numberInString);
}
out.println(s);
}
out.close();
} catch (IOException e) {
System.err.println("Exception" + e);
}
return numberOfMinutes;
}
}

Categories

Resources