C# Can't read some characters from a file - file

New to c# here, I have done some research about this problem but couldn't find anything, lack of vocabulary maybe.
My task here is to a read a huge file and to extract only the lines which are following the conditions.
Code I'm using to test some things:
using (StreamReader sr = new StreamReader("SPDS_Test.doc"))
{
while ((line = sr.ReadLine()) != null)
{
try
{
if (line.Contains("R ") | line.Contains("E "))
{
data = line;
data = data.Remove(0, 1);
data= data.Replace(" ", "").Replace("N", "").Replace("+", ",").Replace("·", ",").Replace("?", ",").Replace("(", "").Replace(")", "");
Data.Add(data);
}
}
catch (Exception e)
{
Console.WriteLine("--------", e);
Console.WriteLine("--------Press any to continue---------");
Console.ReadKey();
}
}
foreach (string d in Data)
{
Console.WriteLine(d);
Console.ReadKey();
}
}
This is a part of the file :
R XRPA168VC
B A
L 手动紧急停堆
E XRPA300KS
A 反应堆停堆 汽轮机停机
R XRPR111VR
B IP
E F2/3(XRPR144KS, XRPR145KS, XRPR146KS)
What I noticed is that the letters aren't even letter if there chinese around it, for example I tried the condition line.Substring(0,1) == "R", it couldn't find those lines.
No matter what I do, my codes would only return this
XPR111VR
F2/3XRPR144KS, XRPR145KS, XRPR146KS
I really need to be able to extract every R and E lines.

I just tried to copy my whole doc into Notepad and put the encoding into UTF8,
seems to work afterward but not sure if it's reliable.

Try this...it works
using (StreamReader sr = new StreamReader("SPDS_Test.doc"))
{
string line;
string data;
List<string> Data = new List<string>();
while ((line = sr.ReadLine()) != null)
{
var utf8 = Encoding.UTF8;
byte[] utfBytes = utf8.GetBytes(line);
string myString = utf8.GetString(utfBytes, 0,
utfBytes.Length);
try
{
if (myString.Contains("R ") || myString.Contains("E "))
{
data = line;
data = data.Remove(0, 1);
data= data.Replace(" ", "").Replace("N",
"").Replace("+", ",").Replace("·", ",").Replace("?",
",").Replace("(", "").Replace(")", "");
Data.Add(data);
}
}
catch (Exception e)
{
Console.WriteLine("--------", e);
Console.WriteLine("--------Press any to continue---------");
Console.ReadKey();
}
}
foreach (string d in Data)
{
Console.WriteLine(d);
Console.ReadKey();
}
}

Related

Check if txt file has text ,if so don't write the same text again?

So right now I'm making a mod in Minecraft where it takes everyones username from a server and adds it to a txt file, it works but the the problem is I don't want to duplicate the names when I use the command again. Nothing has worked so far. How would I check if the txt already contains the username, don't add it again? Thank you. Again, I need it to before writing another name to the list, check the txt file if it already contains the name, if so don't add it.
[code]
for (int i = 0; i < minecraft.thePlayer.sendQueue.playerInfoList.size(); i++) {
List playerList = minecraft.thePlayer.sendQueue.playerInfoList;
GuiPlayerInfo playerInfo = (GuiPlayerInfo) playerList.get(i);
String playerName = StringUtils.stripControlCodes(playerInfo.name);
try {
fileWriter = new FileWriter(GameDirectory() + "\\scraped.txt", true);
bufferedReader = new BufferedReader(new FileReader(GameDirectory() + "\\scraped.txt"));
lineNumberReader = new LineNumberReader(new FileReader(GameDirectory() + "\\scraped.txt"));
} catch (IOException e) {
e.printStackTrace();
}
printWriter = new PrintWriter(fileWriter);
try {
fileWriter.write(playerName + "\r\n");
lineNumberReader.skip(Long.MAX_VALUE);
} catch (IOException e) {
e.printStackTrace();
}
printWriter.flush();
}
addMessage("Scraped " + lineNumberReader.getLineNumber() + " usernames!");
}
[/code]
I've tried this too but with this it doesn't even write anymore.
[code]
List playerList = minecraft.thePlayer.sendQueue.playerInfoList;
for (int i = 0; i < minecraft.thePlayer.sendQueue.playerInfoList.size(); i++) {
GuiPlayerInfo playerInfo = (GuiPlayerInfo) playerList.get(i);
String playerName = StringUtils.stripControlCodes(playerInfo.name);
String lines;
try {
if ((lines = bufferedReader.readLine()) != null) {
if (!lines.contains(playerName)) {
bufferedWriter.write(playerName);
bufferedWriter.newLine();
bufferedWriter.flush();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
int linenumber = 0;
try {
while (lineNumberReader.readLine() != null) {
linenumber++;
}
} catch (IOException e) {
e.printStackTrace();
}
[/code]

Output from reading a text file is repeating lines when appending in Java?

I've made a simple text box which when a button is pressed loads the text from a text file (line by line). It writes the numbers to a JTextArea then it applies some methods to the numbers and outputs the results into a JTextArea.
My problem is that when the output is shown it repeats the lines - it is easier to show by example.
So if the text file reads:
1
2
The output given is:
First TextArea:
1
2
Second TextArea:
resultFrom1
resultFrom1
resultFrom2
So the numbers are displaying fine but the processed data is repeating itself. In this case it shows the program displaying the first result and then displaying both results.
The code for the load button is:
private void loadPlaylistBtnActionPerformed(java.awt.event.ActionEvent evt) {
if (evt.getSource() == loadPlaylistBtn) {
try {
playlistTextArea.setText(null);
FileReader fileReader = new FileReader("playlist.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
String inputFile = "";
String textFieldReadable = bufferedReader.readLine();
while (textFieldReadable != null) {
inputFile += textFieldReadable + "\n";
textFieldReadable = bufferedReader.readLine();
trackNum.setText(inputFile);
String[] loadPlaylist = trackNum.getText().split("\\n");
for (int i = 0; i < loadPlaylist.length; ++i) {
String songName = LibraryData.getName(loadPlaylist[i]);
String songArtist = LibraryData.getArtist(loadPlaylist[i]);
playlistTextArea.append(songName + " - " + songArtist + "\n");
}
}
fileReader.close();
} catch (Exception e) {
System.out.println("File not found.");
}
}
}
The methods in LibraryData are:
getName:
public static String getName(String key) {
try {
stmt = con.createStatement();
ResultSet res = stmt.executeQuery("SELECT * FROM Library WHERE LibraryID = '" +
key + "'");
if (res.next()) {
return res.getString(2);
} else {
return null;
}
} catch (Exception e) {
return null;
}
}
and getArtist:
public static String getArtist(String key) {
try {
stmt = con.createStatement();
ResultSet res = stmt.executeQuery("SELECT * FROM Library WHERE LibraryID = '" + key + "'");
if (res.next()) {
return res.getString(3);
} else {
return null;
}
} catch (Exception e) {
return null;
}
}
Any ideas on how I can make it just output one of the songs relating to the number, rather than repeating itself?
Sorry if this has been really unclear - I'm still quite new to Java.
Thanks :)
Using the assumption that playlistTextArea is your problem test box, the problem seems to be:
playlistTextArea.append(songName + " - " + songArtist + "\n");
You're reading the file lines one at a time, and then appending the entire list every single time, which will result in the pattern 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, etc. Easiest way to resolve this would be to make sure you clear the text box before the for loop (i.e. - Move to the playlistTextArea.setText(null) down).

How to add a condition to read line by line and append text after each line

I want to read each line and find if my line says " Project", then take the substring of that line (substring, 8 - Anything after the word Project) as an example and copy it to the end of each line for every row of line after the fact and up until a new line reads " Project". It should keep looping until the end of my file. This is what I have so far. My script stops and only displays the first line that is being read.
private void CreateFile_Click(object sender, EventArgs e)
{
try
{
var list = new List<string>();
using (var sr = new StreamReader("C:\\File1.txt"))
{
string line;
if ((line = sr.ReadLine()) == " PROJECT")
{
while ((line = sr.ReadLine()) != null)
{
list.Add(line + "DATA");
}
}
else
{
list.Add(line);
}
}
TextBox.Text = string.Join(Environment.NewLine, list.ToArray());
}
catch (Exception ex)
{
MessageBox.Show("An error has occurred" + ex.Message);
}
}
Maybe i have understood your requirement:
using (var sr = new StreamReader("C:\\File1.txt"))
{
string line;
string currentProject = null;
while ((line = sr.ReadLine()) != null)
{
int index = line.IndexOf(" PROJECT", StringComparison.OrdinalIgnoreCase);
if (index >= 0)
currentProject = line.Substring(index + 9);
else
list.Add(string.Format("{0} {1}",line, currentProject));
}
}
You have two ReadLine in the if which advances the reader to the next line.

how do I make Selenium webdriver to read a csv file to perform an action

how do I make Selenium webdriver to read a csv file to perform an action. I have my script to load it in the browser and perform an action how do I make it to read csv file and replace that action with the data in the csv file
The best way to do this would be to use another library that specializes in such parsing, and feed it into memory. A good StackOverflow question regarding this is here.
Remember that WebDriver simply interacts with a browser. It's the language that your writing in that does file IO. I'd suggest creating a CSV class. Since csv is just a text file, you can read it in as a string and iterate through each line. Split by commas and you're good to go. You didn't specify a language so here is an example in C# from our library. Notice I use yield for efficiency. This was something I found somewhere. No need to reinvent the wheel.
public static class CSV
{
private static bool ignoreFirstLineDefault = false;
public static IEnumerable<IList<string>> FromFile(string fileName)
{
foreach (IList<string> item in FromFile(fileName, ignoreFirstLineDefault)) yield return item;
}
public static IEnumerable<IList<string>> FromFile(string fileName, bool ignoreFirstLine)
{
using (StreamReader rdr = new StreamReader(fileName))
{
foreach (IList<string> item in FromReader(rdr, ignoreFirstLine)) yield return item;
}
}
public static IEnumerable<IList<string>> FromStream(Stream csv)
{
foreach (IList<string> item in FromStream(csv, ignoreFirstLineDefault)) yield return item;
}
public static IEnumerable<IList<string>> FromStream(Stream csv, bool ignoreFirstLine)
{
using (var rdr = new StreamReader(csv))
{
foreach (IList<string> item in FromReader(rdr, ignoreFirstLine)) yield return item;
}
}
public static IEnumerable<IList<string>> FromReader(TextReader csv)
{
//Probably should have used TextReader instead of StreamReader
foreach (IList<string> item in FromReader(csv, ignoreFirstLineDefault)) yield return item;
}
public static IEnumerable<IList<string>> FromReader(TextReader csv, bool ignoreFirstLine)
{
if (ignoreFirstLine) csv.ReadLine();
IList<string> result = new List<string>();
StringBuilder curValue = new StringBuilder();
char c;
c = (char)csv.Read();
while (csv.Peek() != -1)
{
switch (c)
{
case ',': //empty field
result.Add("");
c = (char)csv.Read();
break;
case '"': //qualified text
case '\'':
char q = c;
c = (char)csv.Read();
bool inQuotes = true;
while (inQuotes && csv.Peek() != -1)
{
if (c == q)
{
c = (char)csv.Read();
if (c != q)
inQuotes = false;
}
if (inQuotes)
{
curValue.Append(c);
c = (char)csv.Read();
}
}
result.Add(curValue.ToString());
curValue = new StringBuilder();
if (c == ',') c = (char)csv.Read(); // either ',', newline, or endofstream
break;
case '\n': //end of the record
case '\r':
//potential bug here depending on what your line breaks look like
if (result.Count > 0) // don't return empty records
{
yield return result;
result = new List<string>();
}
c = (char)csv.Read();
break;
default: //normal unqualified text
while (c != ',' && c != '\r' && c != '\n' && csv.Peek() != -1)
{
curValue.Append(c);
c = (char)csv.Read();
}
result.Add(curValue.ToString());
curValue = new StringBuilder();
if (c == ',') c = (char)csv.Read(); //either ',', newline, or endofstream
break;
}
}
if (curValue.Length > 0) //potential bug: I don't want to skip on a empty column in the last record if a caller really expects it to be there
result.Add(curValue.ToString());
if (result.Count > 0)
yield return result;
}
}
I suggest you to use Excel files instead of csv. limitation while using CSV is when you want to use the delimiter ',' in the data itself e.g. if you you have an address field say Gyandeep Colony, B. No : - 1/5 here the ',' make break your code.
The way i do reading of data is by using my Utility Code
public class ExcelHandler {
public static String getSheetData(String path,String sheetName, int col , int row) {
Workbook workbook;
String data = null;
try {
workbook = Workbook.getWorkbook(new File(path));
Sheet sheet = workbook.getSheet(sheetName);
data = sheet.getCell(row,col).getContents();
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
public static String getSheetData(String path, int sheetNo, int col , int row) {
Workbook workbook;
String data = null;
try {
workbook = Workbook.getWorkbook(new File(path));
Sheet sheet = workbook.getSheet(sheetNo);
data = sheet.getCell(row,col).getContents();
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
}
I just call these method wherever i want in my code .
Lets take an example
WebElement username = driver.findElement(By.id("username"));
username.sendKeys(Utility.getSheetData("Login.xls",0,1,0));
Happy Coding :)
FileInputStream file = new FileInputStream(new File("C:\\testdata.xls"));
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
for (int i=1; i <= sheet.getLastRowNum(); i++){
String keyword = sheet.getRow(i).getCell(0).getStringCellValue();
searchbox.sendKeys(keyword);
searchbox.submit();
driver.manage().timeouts().implicitlyWait(10000, TimeUnit.MILLISECONDS);
}
workbook.close();
file.close();

Need help fixing a try, catch error

I am trying to write a method that prints information into an array. the directions are: Create a second method for WordPath:
makeWordArray that takes a String file name as input, and it returns either an array or an ArrayList that stores WordData objects.
First, the method should open the file with new FileReader(file), call the numLines method to get the number of lines in file, and then create an array or an ArrayList of that size.
Next, close the FileReader and reopen the file. This time use BufferedReader br = new BufferedReader(new FileReader(file)). Create a loop to run through the file calling br.readLine(). For each line that you read in from br.readLine(), call the parseWordData on that String to get a WordData and store the WordData object into the appropriate index of the array or ArrayList.
My code is:
public class WordPath {
public static int numLines(Reader reader) {
BufferedReader br = new BufferedReader(reader);
int lines = 0;
try {
while(br.readLine() != null) {
lines = lines + 1;
}
br.close();
}
catch (IOException ex) {
System.out.println("You have reached an IOException");
}
return lines;
}
public WordData[] makeWordArray(String file) {
try {
FileReader fr = new FileReader(file);
int nl = numLines(fr);
WordData[] newArray = new WordData[nl];
fr.close();
BufferedReader br = new BufferedReader(new FileReader(file));
while(br.readLine() != null) {
int arrayNum = 0;
newArray[arrayNum] = WordData.parseWordData(br.readLine());
arrayNum = arrayNum + 1;
}
}
catch (IOException ex) {
System.out.println("You have reached an IOException");
}
catch (FileNotFoundException ex2) {
System.out.println("You have reached a FileNotFoundexception");
}
return newArray;
}
}
I am running int a problem where the variable newArray can not be found, I believe because it is in the try statement. Is there any way to reformat this to work?
Like this:
public WordData[] makeWordArray(String file) {
WordData[] newArray = null;
try {
FileReader fr = new FileReader(file);
int nl = numLines(fr);
newArray = new WordData[nl];
fr.close();
BufferedReader br = new BufferedReader(new FileReader(file));
while(br.readLine() != null) {
int arrayNum = 0;
newArray[arrayNum] = WordData.parseWordData(br.readLine());
arrayNum = arrayNum + 1;
}
}
catch (IOException ex) {
System.out.println("You have reached an IOException");
}
catch (FileNotFoundException ex2) {
System.out.println("You have reached a FileNotFoundexception");
}
return newArray;
}
You need to pull the declaration of the variable outside, but leave the assignment to that variable on the inside of the try.

Resources