public static void main(String[] args) throws IOException {
String dataRow;
BufferedReader CSVFile =
new BufferedReader(new FileReader("test.csv"));
while ((dataRow = CSVFile.readLine()) != null) {
System.out.println(dataRow.split(";")[0]);
}
// Close the file once all data has been read.
CSVFile.close();
// End the printout with a blank line.
System.out.println("Done");
}
The CSV file I am Trying to read in normal text view
ID;Numbers
12;234
343;233
All I am able to print is space no strings in it.
Output
1. ��I
2.
3.
4.
Done
The File Encoding is Only "UNICODE"
How to read a Unicode file in java.
Do I have to set a parameter setting the encoding type of the file in FileReader java class construtor??
Kindly advise.
public static void main(String[] args) throws IOException {
String dataRow;
BufferedReader CSVFile = new BufferedReader(new FileReader("F:\\csv.csv"));
while ((dataRow = CSVFile.readLine()) != null) {
String []data = dataRow.split(";");
for (String d : data) {
System.out.print(d + " ");
}
System.out.println();
}
CSVFile.close();
System.out.println("Done");
}
The result is shown below:
ID Numbers
12 234
343 233
Done
The way to get the file encode is shown below
open the csv file with nodepad editor, then click file -> save as
if you file encoding is unicode, when you read file,you can pass a file encodeing argument to function
the fllowing code is below
public static void main(String[] args) throws IOException {
String dataRow;
BufferedReader CSVFile = new BufferedReader(new InputStreamReader(new FileInputStream("F:\\csv.csv"),"unicode"));
while ((dataRow = CSVFile.readLine()) != null) {
String []data = dataRow.split(";");
for (String d : data) {
System.out.print(d + " ");
}
System.out.println();
}
CSVFile.close();
System.out.println("Done");
}
if you do not pass the file encoding argument, when you read the file content, the encoding depends on your os
Related
i'm trying to replace some letters in txt file and rewrite it but i can't keep indents at all.
Source file looks like this :
aaaaaaaaaWRPaaaaaaaa
bbbWRPbbbbbbbbbbbbbb
here's what i've tried :
public static void fileReader (String path) throws FileNotFoundException, IOException {
File prevfile = new File(path);
BufferedReader reader = new BufferedReader(new FileReader(prevfile));
String line = reader.readLine();
while (line!=null){
content = content + line + "\n" ;
line = reader.readLine();
}
String newCOntent = content.replaceAll("WRP","WRD");
FileWriter writer = new FileWriter(prevfile);
writer.write(newContent);
writer.close();
reader.close();
}
}
after which i get output in a single line.
I have a situation similar where I need to change a line in a batch file if similar string not found.
Suppose I have a code like below in batch(I know it is not correct code as it a dummy only)
public static void main(String[] args) {
if (user == '1234') {
ENV DEV
set DB myDBDEV
set Excel myExecelDEV
set API MyAPIURLDEV
} elseif (user == '5678') {
ENV UAT
set DB myDBUAT
set Excel myExecelUAT
set API MyAPIURLUAT
}
}
}
Now I want java to read above file, find ENV as DEV and change the value like myDBDEV, myExecelDEV, MyAPIURLDEV etc.
I am able to find the line number by using below code
FileInputStream fis = new FileInputStream("C:\\Users\\owner\\Desktop\\batch\\MYbatch-env.csh");
InputStreamReader input = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(input);
String data;
String result = new String();
int i=0;
while ((data = br.readLine()) != null) {
i++;
if(data.contains("ENV DEV")) {
System.out.println("line number -> "+i);
}
result = result.concat(data + "\n");
}
I have tried below code but that was not return line number so I use above approach
Finding line number of a word in a text file using java
I also tried below approach but it seems not working
How to replace an string after a specific line in a file using java
Now problem statement is replaceAll function will remove all key but I want to remove the next string of key means value. and it is a text as string not a hashmap kind thing,
In if block if DB string is myDBDEV2 then I want to change the values to myDBDEV
Example:
If below string found
ENV DEV
Then below value should check value of key DB and replace if not found required value
set DB myDBDEV
set Excel myExecelDEV
set API MyAPIURLDEV
And main thing is code should make change in if block only, else if variables should be affected as an file example I have shown in above URL.
Below solution work for me
public static void main(String[] args) throws Exception {
String filepath= "C:\\Users\\Demo\\Desktop\\batch\\Demo.sh";
FileInputStream fis = new FileInputStream(filepath);
InputStreamReader input = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(input);
String data;
String result = new String();
int lineNumber=0;
int i=0;
while ((data = br.readLine()) != null) {
i++;
if(data.contains("My String data")) {
System.out.println("line number -> "+i);
lineNumber=i;
break;
}
result = result.concat(data + "\n");
}
br.close();
lineNumber=lineNumber+1;
System.out.println(lineNumber);
String Mystring =" Mystring";
String Mystringline = Files.readAllLines(Paths.get(filepath)).get(lineNumber-1); // get method count from 0 so -1
System.out.println("Line data ->> "+Mystringline);
if(!Mystringline.equalsIgnoreCase(Mystring)) {
setVariable(lineNumber, Mystring, filepath);
}else {
System.out.println("Mystring is already pointing to correct DB");
}
System.out.println("Succesfully Change");
}
public static void setVariable(int lineNumber, String data, String filepath) throws IOException {
Path path = Paths.get(filepath);
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
lines.set(lineNumber - 1, data);
Files.write(path, lines, StandardCharsets.UTF_8);
}
}
i'm trying to read a FASTA file into a string in java.
My code works fine with small files, but when I choose a real FASTA file
which includes 5 million chars, so I can use this string, the program get stucked. get stucked= i see no output, and the program becomes with black screen.
public static String ReadFastaFile(File file) throws IOException{
String seq="";
try(Scanner scanner = new Scanner(new File(file.getPath()))) {
while ( scanner.hasNextLine() ) {
String line = scanner.nextLine();
seq+=line;
// process line here.
}
}
return seq;
}
Try to use a StringBuilder to process big loads of text data:
public static String ReadFastaFile( File file ) throws IOException {
StringBuilder seq = new StringBuilder();
try( Scanner scanner = new Scanner( file ) ) {
while ( scanner.hasNextLine() ) {
String line = scanner.nextLine();
seq.append( line );
// process line here.
}
}
return seq.toString();
}
I would try to use BufferedReader to read the file, something like this:
public static String readFastaFile(File file) throws IOException {
String seq="";
try(BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
// process line here.
}
}
return seq;
}
And also concatenate with StringBuilder like davidbuzatto said.
I have a text file with an integer on each line, ordered from least to greatest, and I want to put them in a new text file with any duplicate numbers removed.
I've managed to read in the text file and print the numbers on the screen, but I'm unsure on how to actually write them in a new file, with duplicates removed?
public static void main(String[] args)
{
try
{
FileReader fr = new FileReader("sample.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
out.println(str + "\n");
}
br.close();
}
catch (IOException e) {
out.println("File not found");
}
}
When reading the file, you could add the numbers to a Set, which is a data structure that doesn't allow duplicate values (just Google for "java collections" for more details)
Then you iterate through this Set, writing the numbers to a FileOutputStream (google for "java io" for more details)
Instead of printing each of the numbers, add them to an Array. After you've added all the integers, you can cycle through the array to remove duplicates (sample code for this can be found fairly easily).
Once you have an array, use BufferedWriter to write to an output file. Example code for how to do this can be found here: https://www.mkyong.com/java/how-to-write-to-file-in-java-bufferedwriter-example/
Alternatively, use a Set, and BufferedWriter should still work in the same way.
assuming the input file is already ordered:
public class Question42475459 {
public static void main(final String[] args) throws IOException {
final String inFile = "sample.txt";
try (final Scanner scanner = new Scanner(new BufferedInputStream(new FileInputStream("")), "UTF-8");
BufferedWriter writer = new BufferedWriter(new FileWriter(inFile + ".out", false))) {
String lastLine = null;
while (scanner.hasNext()) {
final String line = scanner.next();
if (!line.equals(lastLine)) {
writer.write(line);
writer.newLine();
lastLine = line;
}
}
}
}
}
I've a code which replaces 10:A to 12:A in a text file called sample.txt. Also, the code I've now is changing the file format, which shouldn't. Can someone please let me know how to do the same using regular expression in Java which doesn't change the file format? File has original format as below 10:A 14:Saxws But after executing the code it outputs as 10:A 14:Saxws.
import java.io.*;
import java.util.*;
public class FileReplace
{
List<String> lines = new ArrayList<String>();
String line = null;
public void doIt()
{
try
{
File f1 = new File("sample.txt");
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null)
{
if (line.contains("10:A"))
line = line.replaceAll("10:A", "12:A") + System.lineSeparator();
lines.add(line);
}
fr.close();
br.close();
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
for(String s : lines)
out.write(s);
out.flush();
out.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public static void main(String[] args)
{
FileReplace fr = new FileReplace();
fr.doIt();
}
}
It looks like your OS or editor is not able to print correctly line separators generated by System.lineSeparator(). In that case consider
reading content of entire file to string (including original line separators), - then replacing part which you are interested in
and writing replaced string back to your file
You can do it using this code:
Path file = Paths.get("sample.txt");
//read all bytes from file (they will include bytes representing used line separtors)
byte[] bytesFromFile = Files.readAllBytes(file);
//convert themm to string
String textFromFile = new String(bytesFromFile, StandardCharsets.UTF_8);//use proper charset
//replace what you need (line separators will stay the same)
textFromFile = textFromFile.replaceAll("10:A", "12:A");
//write back data to file
Files.write(file, textFromFile.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE);